XML indention code also modifies XML code?!

XML indention code also modifies XML code?!

Post by bWFydGl » Thu, 16 Feb 2006 18:28:26


I've written a small snippet of code that indents XML. Somehow it seems to
modify the XML code too (not just the whitespace but it actually remove one
element). This is my code:

http://www.yqcomputer.com/

This is the XML unidented XML code that I use:

<?xml version='1.0' encoding='UTF-8'?><soap:Envelope
xmlns:soap=' http://www.yqcomputer.com/ '><soap:Body><soap:Fault><soap:faultcode>101</soap:faultcode><soap:faultstring>MustUnderstand.MyHeader</soap:faultstring><soap:detail/></soap:Fault></soap:Body></soap:Envelope>


And here is how the XML code comes out once indented:

<?xml version='1.0' encoding='UTF-8'?>
<soap:Body xmlns:soap=" http://www.yqcomputer.com/ ">
<soap:Fault>
<soap:faultcode>101</soap:faultcode>
<soap:faultstring>MustUnderstand.MyHeader</soap:faultstring>
<soap:detail />
</soap:Fault>
</soap:Body>


At first I thought this was correct output because it looks so good. BUT,
notice that the soap:Envelope element that wraps the soap:Body element is
missing in the output. Why?

After some experimentation I have come to believe that the XML declaration
tag has something to do with it. ie the part that says:

<?xml version='1.0' encoding='UTF-8'?>
 
 
 

XML indention code also modifies XML code?!

Post by Martin Hon » Thu, 16 Feb 2006 21:54:01


If you simply want to copy everything then don't call the read method
explicitly yourself, simply call WriteNode on the original reader e.g.

string inputXml = "<?xml version='1.0'
encoding='UTF-8'?><soap:Envelope
xmlns:soap=' http://www.yqcomputer.com/ '><soap:Body><soap:Fault><soap:faultcode>101</soap:faultcode><soap:faultstring>MustUnderstand.MyHeader</soap:faultstring><soap:detail/></soap:Fault></soap:Body></soap:Envelope>";
StringBuilder indentedXml = new StringBuilder();
XmlTextWriter writer = new XmlTextWriter(new StringWriter(indentedXml));
writer.Formatting = Formatting.Indented;
writer.Indentation = 4;
XmlTextReader reader = new XmlTextReader(new StringReader(inputXml));
reader.WhitespaceHandling = WhitespaceHandling.None;

writer.WriteNode(reader, false);

reader.Close();
writer.Flush();
writer.Close();

//use indentedXml.ToString() to have indented markup as string


--

Martin Honnen --- MVP XML
http://www.yqcomputer.com/