What is the simplest way to get indented XML with line breaks from XmlDocument?


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?

10/15/2008 2:25:59 AM

Accepted Answer

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)) {
    return sb.ToString();

It's a bit more code than I hoped for, but it works just peachy.

1/22/2015 8:53:45 AM

As adapted from Erika Ehrli's blog, this should do it:

XmlDocument doc = new XmlDocument();
// Save the document to a file and auto-indent the output.
using (XmlTextWriter writer = new XmlTextWriter("data.xml", null)) {
    writer.Formatting = Formatting.Indented;

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow