Search code examples
c#.netxmldocumentouterxml

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?


Solution

  • 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.