When I build XML up from scratch with XmlDocument
, the OuterXml
property already has everything nicely indented with line breaks. However, if I call LoadXml
on some very "compressed" XML (no line breaks or indention) then the output of OuterXml
stays that way. So ...
What is the simplest way to get beautified XML output from an instance of XmlDocument
?
In Text mode when you select one of the format and indent actions (Document > Source > Format and Indent, Document > Source > Indent Selection, or Document > Source > Format and Indent Element).
Indenting XML tags is never required for parsing. However, the point of XML is to be human as well as machine readable, so indentation is generally worth having, as it makes it far easier for human readers to work with and take in the structure at a glance.
Use XmlDocument. Load() method to load XML from your file. Then use XmlDocument. InnerXml property to get XML string.
The XmlDocument class does not implement IDisposable , so there's no way to force it to release it's resources at will. If you need to free that memory the only way to do that would be xmlDocument = null; and garbage collection will handle the rest.
Based on the other answers, I looked into XmlTextWriter
and came up with the following helper method:
static public string Beautify(this XmlDocument doc) { StringBuilder sb = new StringBuilder(); XmlWriterSettings settings = new XmlWriterSettings { Indent = true, IndentChars = " ", NewLineChars = "\r\n", NewLineHandling = NewLineHandling.Replace }; using (XmlWriter writer = XmlWriter.Create(sb, settings)) { doc.Save(writer); } return sb.ToString(); }
It's a bit more code than I hoped for, but it works just peachy.
As adapted from Erika Ehrli's blog, this should do it:
XmlDocument doc = new XmlDocument(); doc.LoadXml("<item><name>wrench</name></item>"); // Save the document to a file and auto-indent the output. using (XmlTextWriter writer = new XmlTextWriter("data.xml", null)) { writer.Formatting = Formatting.Indented; doc.Save(writer); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With