XmlDocument Save and Load Streams

  • Thread starter Thread starter Guest
  • Start date Start date
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" )
 
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.
 
Back
Top