How to indent an XML file or document

Office has a deeper integration with XML technology and developers are always looking for tips and tricks to work with XML documents. Office provides support to work with XML and you might be one of those developers that is programmatically generating Word documents (using WordprocessingML) , Excel spreadsheets (using SpreadsheetML), PowerPoint slides (using PresentationML), or Visio diagrams using (DataDiagrammingML). I think it always comes handy to have a list of tips and tricks to work with XML, and today I will share with you three simple ways of indenting an XML file/document.

Indenting XML files might sound as one of those netpick or nice-to-have enhancements that you don’t really need when you are working with XML. However, lots of applications and tools generate programmatically XML files and it always comes handy to open a nice and readable indented XML file instead of a “how can I edit this!” single line of eternal XML elements.

For managed applications:

  • If you are generating XML files using and XmlTextWriter, you just need to do the following:

    [VB.NET]
    Dim writer as XmlTextWriter = new XmlTextWriter("data.xml",nothing)
    writer.Formatting = Formatting.Indented

    [C#]
    XmlTextWriter writer = new XmlTextWriter("data.xml",null);
    writer.Formatting = Formatting.Indented;

  • If you are generating XML files/documents using DOM (XmlDocument) , you can add an XmlTextWriter to indent the code and you will be done:

    [VB.NET]
    Dim doc as XmlDocument = new XmlDocument()
    ' Save the document to a file and auto-indent the output.
    Dim writer as XmlTextWriter = new XmlTextWriter("data.xml",nothing)
    writer.Formatting = Formatting.Indented
    doc.Save(writer)

    [C#]
    XmlDocument doc = new XmlDocument();
    doc.LoadXml("<item><name>wrench</name></item>");
    // Save the document to a file and auto-indent the output.
    XmlTextWriter writer = new XmlTextWriter("data.xml",null);
    writer.Formatting = Formatting.Indented;
    doc.Save(writer);

For any platform:

  • If you are generating XML files using an XSL transform file, you just need to add a simple line to your XSL file.

    <?xml version="1.0"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
      <xsl:output method="xml" omit-xml-declaration="no" indent ="yes"  encoding="US-ASCII"/>

Happy Office XML programming!