JCCyC JCCyC - 2 months ago 18
C# Question

Best way to prettify an XmlDocument (.NET)?

Let's say I have a

System.Xml.XmlDocument
whose
InnerXml
is:

<comedians><act id="1" type="single" name="Harold Lloyd"/><act id="2" type="duo" name="Laurel and Hardy"><member>Stan Laurel</member><member>Oliver Hardy</member></act></comedians>


I'd like to format it thusly, with newlines and whitespace added:

<comedians>
<act id="1" type="single" name="Harold Lloyd"/>
<act id="2" type="duo" name="Laurel and Hardy">
<member>Stan Laurel</member>
<member>Oliver Hardy</member>
</act>
</comedians>


I looked in the
XmlDocument
class for some prettifying method, but couldn't find one.

Answer

Basically you can use XmlDocument.Save(Stream) and pass any Stream as target to receive the xml content. Including a "memory-only" StringWriter as below:

string xml = "<myXML>";

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);

using(StringWriter sw = new StringWriter())
{
    doc.Save(sw);
    Console.Write(sw.GetStringBuilder().ToString());
}

Update: using block

Comments