all groups > dotnet xml > march 2006 >
You're in the

dotnet xml

group:

MemoryStream, Backslash-Zero Problem


MemoryStream, Backslash-Zero Problem rasx
3/9/2006 6:29:27 PM
dotnet xml:
I get this error when I fail to ‘clean up’ my UTF-8 MemoryStream: “Invalid at
the top level of the document. Error processing resource…” Visual Studio 2005
in debug mode shows well formed XML “prepended” with a character represented
by an empty rectangle and trailed with a series of backslash zeros (\0).
These are the lines of code that solve this problem:

s = s.Trim();
s = s.Replace("\0", String.Empty);

The Trim() gets rid of the “prepended” mystery character and the second line
explains itself. Why do I need these two line of code? Here is more context:

MemoryStream ms = new MemoryStream();
XmlTextWriter xw = new XmlTextWriter(ms,Encoding.UTF8);

//do XMLWriter stuff…

xw.Flush();
s = Encoding.UTF8.GetString(ms.GetBuffer());

s = s.Trim();
s = s.Replace("\0", String.Empty);

xml = new XmlDocument();
xml.LoadXml(s);

By the way, I get the same error when keep everything in the MemoryStream
and make the statement xml.Load(ms). I see no “stream visualizer” for
debugging purposes.

--
Bryan, Emperor of String.Empty
Re: MemoryStream, Backslash-Zero Problem dickster
3/10/2006 1:21:41 AM
I have seen that empty rectangle before- seems like default behaviour
-why I have no idea.

There is a parameter "encoderShouldEmitUTF8Identifier" (type Boolean)
as one of the options on the constructor of the
System.Text.UTF8Encoding


So add these 2 lines
--------------------------------------------------------
System.text.UTF8Encoding enc;
enc = New System.text.UTF8Encoding(False);
--------------------------------------------------------

And change your code to this
--------------------------------------------------------
MemoryStream ms = new MemoryStream();
XmlTextWriter xw = new XmlTextWriter(ms,enc);
--------------------------------------------------------

Dickster
Re: MemoryStream, Backslash-Zero Problem rasx
3/12/2006 8:07:28 PM
The short answer to the earlier post is, ‘Don’t use a MemoryStream object
with an XmlWriter.’ The expected results are received in my case when an
HttpContext.Response.OutputStream is used instead.
--
Bryan, Emperor of String.Empty
http://songhaysystem.com


[quoted text, click to view]
Re: MemoryStream, Backslash-Zero Problem Amol Kher [MSFT]
3/31/2006 12:21:38 AM
I think the issue you are seeing is because you dont set the MemoryStream
back to its initial position before passing it into the Dom?

ms.Seek( 0, SeekOrigin.Begin );


[quoted text, click to view]

AddThis Social Bookmark Button