XmlDocument Save and Load Streams

G

Guest

I have created an XmlDocument and can see that this is correctly formed and has a root element
If I Save the doc to a file and reload it all works o
If I dump the doc to a stream, again using the Save method, and write this to a file I can then reload this correctly.

However since I have no need to write the data to file I want to save it as a stream then reload it the stream.
However If I do this I have suddenly lost the root element

<<I am actually going to create an XmlTextReader from the stream but the above demonstrates my problem >><<(which occurs also when trying to read an XmlTextReader created from the stream) >

Can anyone explain what I am doing wrong

CODE
THIS FAIL
XmlDocument xmlDoc = GetXmlDoc( ); // Returns an XmlDocument
MemoryStream xmlStream = new MemoryStream( )
xmlDoc.Save( xmlStream )
xmlDoc.Load( xmlStream ); // Exception thrown here - root element is missin

THIS WORK
XmlDocument xmlDoc = GetXmlDoc( ); // Returns an XmlDocument
MemoryStream xmlStream = new MemoryStream( )
xmlDoc.Save( "C:\\TEMP\\TEST.xml" )
xmlDoc.Load( "C:\\TEMP\\TEST.xml" )
 
J

Jon Skeet [C# MVP]

Tom Pearson said:
I have created an XmlDocument and can see that this is correctly formed
and has a root element.
If I Save the doc to a file and reload it all works ok
If I dump the doc to a stream, again using the Save method, and write
this to a file I can then reload this correctly.

However since I have no need to write the data to file I want to save
it as a stream then reload it the stream.
However If I do this I have suddenly lost the root element.

<<I am actually going to create an XmlTextReader from the stream but
the above demonstrates my problem >><<(which occurs also when trying
to read an XmlTextReader created from the stream) >>

Can anyone explain what I am doing wrong?

CODE:
THIS FAILS
XmlDocument xmlDoc = GetXmlDoc( ); // Returns an XmlDocument
MemoryStream xmlStream = new MemoryStream( );
xmlDoc.Save( xmlStream );
xmlDoc.Load( xmlStream ); // Exception thrown here - root element is missing

Yup - you're trying to load from the *end* of the stream. If you use:

xmlDoc.Save(xmlStream);
xmlStream.Flush();
xmlStream.Position=0;
xmlDoc.Load(xmlStream);

it should work fine.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top