Text formatting and System.Xml
Date: 09/25/05
(C Sharp) Keywords: xml
I am having a bit of a rough time with System.Xml, namely getting the XML that one of my classes generates to Load() back into an XmlDocument.
I am creating the XML with an XmlTextWriter using UTF-8 encoding. I write out the XML, obeying the spec to a fault. Everything is fine to this point.
Now, depending on how I load the XML back into a new XmlDocument, I get an error, or not. To wit:
Scenario 1: After I generate the XML, I write it straight to a text file using a StreamWriter (two lines: writer.Write(thisXML) and writer.Close()). Then, I make a new XmlDocument(), and call thisDoc.Load("myXMLFile.txt"). In this scenario, everything loads fine -- all of the document's children are available, and there are no exceptions.
The thing is, I'd like to avoid the whole writing to a text file bit, and keep it all in memory.
Scenario 2: After I generate the XML, I store it in a string. Then, I make a new XmlDocument(), and call thisDoc.LoadXml(myXMLString). In this scenario, on the line immediately following the LoadXml() method, I get a "System Error" exception from System.Xml. No other information from the exception.
I've put the contents of the XML string into a text box, and copied-pasted into several online XML schema checkers, and there are no errors. As a matter of fact, the EXACT SAME XML loads perfectly fine from a file.
I've also tried copying the string into a MemoryStream and calling thisDoc.Load(thisMemStream), figuring that maybe LoadXml() and Load() were different. Even using the memorystream, I get the same "System Error" exception.
What gives? Is it something with how UTF-8 is stored in a string vs. how it is stored in the file system? Is the file system doing something to the text representation that subsequently allows the System.Xml reader to successfully load the XML stream?
Argh. Any help appreciated.
Source: http://www.livejournal.com/community/csharp/36306.html