Beautifying XML Output from XmlDocument Using XmlWriterSettings

Dec 07, 2025 · Programming · 8 views · 7.8

Keywords: C# | .NET | XmlDocument | XML formatting | XmlWriterSettings

Abstract: This article explores how to transform compressed XML in XmlDocument into a beautified format with indentation and line breaks in C# .NET. It details the configuration of key properties in XmlWriterSettings, such as indentation and newline handling, and provides complete code examples and best practices. By comparing different methods, it emphasizes that using XmlWriter.Create is superior to the obsolete XmlTextWriter, while explaining the core principles of XML formatting and common application scenarios.

Importance of XML Format Beautification

In C# .NET development, the XmlDocument class is commonly used for handling XML data. When loading compressed XML (i.e., without indentation or line breaks) via the LoadXml method, its OuterXml property retains the original format, making the output difficult to read and debug. Beautifying XML format not only enhances readability but also facilitates manual editing and version control. For example, comparing <item><name>wrench</name></item> with a formatted version shows the latter's advantage in complex data structures.

Core Solution: The XmlWriterSettings Class

Based on the best answer, the simplest approach is to use the XmlWriterSettings class to configure output format. Create an extension method Beautify that utilizes XmlWriter.Create to generate a beautified string. Key steps include:

  1. Initialize a StringBuilder to store the result.
  2. Configure XmlWriterSettings properties:
    • Indent = true: Enables indentation.
    • IndentChars = " ": Sets indentation characters to two spaces.
    • NewLineChars = "\r\n": Defines newline characters.
    • NewLineHandling = NewLineHandling.Replace: Ensures consistent newline handling.
  3. Use a using statement to create an XmlWriter instance and call doc.Save(writer) to save the document.
  4. Return the string representation from StringBuilder.

Code example:

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();
}

This method automatically adds formatting during the serialization process via XmlWriter, without manual node manipulation.

Alternative Method: Obsolete Usage of XmlTextWriter

Referencing other answers, an older method uses the XmlTextWriter class, but it is obsolete. Example:

using (XmlTextWriter writer = new XmlTextWriter("data.xml", null)) {
    writer.Formatting = Formatting.Indented;
    doc.Save(writer);
}

Although simple, XmlTextWriter is not recommended after .NET Framework 2.0 due to its lack of flexible configuration like XmlWriterSettings. For instance, it cannot easily customize indentation characters or handle newlines. Therefore, modern development should prioritize the XmlWriter.Create-based approach.

Technical Details and Best Practices

The core of beautifying XML lies in controlling the output stream. When the XmlDocument.Save method accepts an XmlWriter parameter, it formats the XML according to its settings. Key points include:

In practice, this method can be integrated into logging or API responses to improve the development experience. For example, output beautified XML to the console during debugging: Console.WriteLine(doc.Beautify());.

Conclusion and Extensions

Beautifying XmlDocument output via XmlWriterSettings is an efficient and standardized method. It addresses the readability issues of compressed XML while keeping code concise. Developers should avoid the obsolete XmlTextWriter and adopt the modern settings-based pattern. In the future, explore formatting options in XML serialization libraries like System.Xml.Linq (LINQ to XML) for more complex scenarios.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.