Reputation: 16622
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.
Upvotes: 2
Views: 826
Reputation: 5640
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
Upvotes: 5
Reputation: 16622
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.
Upvotes: 0
Reputation: 10184
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.
Upvotes: -3