Arvo Bowen Arvo Bowen -4 years ago 119
C# Question

XMLDocument.Save adds return carriages to XML when elements are blank

I'm loading a XML Document that has some tags that have no innertext.

If I populate the innertext with some data then it works as needed (you get opening tag, innertext and closing tag all on one line) like the following...

<root>
<element>value</element>
</root>


The problem arises with tags with no values. These SHOULD be displayed in the same way as above with the exception of no value of coarse, like the following...

<root>
<element></element>
</root>


However, when the innertext has an empty string it adds a carriage return & line feed which is not what is expected! It ends up looking like the following...

<root>
<element>
</element>
</root>


This is my current code that yields the above results...

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"C:\test.xml");

//Save the xml and then cleanup
xmlDoc.Save(@"C:\test.xml");

Answer Source

This fixed it for me...

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"C:\test.xml");

//Save the xml and then cleanup
XmlWriterSettings settings = new XmlWriterSettings { Indent = true };
XmlWriter writer = XmlWriter.Create(@"C:\test.xml", settings);
xmlDoc.Save(writer);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download