tags:

views:

303

answers:

3

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.

+4  A: 

Basically you can use XmlDocument.Save(Stream) and pass any Stream as target to recieve 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

Eduardo Cobuci
You've tested that? It indents? Also -1 for no using blocks.
John Saunders
You should try it before ask, and pay more attention before downvote...
Eduardo Cobuci
The downvote was for the lack of using blocks.
John Saunders
Sorry but I'm using...
Eduardo Cobuci
@Eduardo: you're correct that doc.Save indents. I'll remove the downvote for that. doc.WriteTo does not. And you want using (StringWriter sw = new StringWriter()) {doc.Save(sw); Consolw.Write(sw.ToString());}
John Saunders
@Eduardo, if you implement using blocks, I'll upvote you.
John Saunders
@John: Sure good point. Edited!
Eduardo Cobuci
A: 

Trying to prettify XML is like putting lipstick on a pig :) It still ain't gonna be pretty.

Why are you trying to prettify it? If it is for editing purposes, Visual Studio does a pretty good job of presenting it in readable form. If it is for a user, then they may prefer to just open up in their preferred editor or explorer.

Larry Watanabe
Debugging output.
JCCyC
A: 

Jon Galloway posted an answer and deleted it, but it was actually the best option for me. It went somewhat like this:

StringBuilder Prettify(XmlDocument xdoc)
{
    StringBuilder myBuf = new StringBuilder();
    XmlTextWriter myWriter = new XmlTextWriter(new StringWriter(myBuf));
    myWriter.Formatting = Formatting.Indented;
    xdoc.Save(myWriter);
    return myBuf;
}

No need to create a XmlWriterSettings object.

JCCyC
Yes, but he was wrong for two other reasons, which is why he deleted it. Don't use XmlTextWriter. Also, you need using blocks. It turns out that XmlDocument.Save by itself is all you need for indentation.
John Saunders
What, exactly, happens if I don't use using?
JCCyC