Compartilhar via


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="https://www.w3.org/1999/XSL/Transform">
      <xsl:output method="xml" omit-xml-declaration="no" indent ="yes"  encoding="US-ASCII"/>

Happy Office XML programming!

Comments

  • Anonymous
    November 16, 2005
    Yes, very nice Tip.

  • Anonymous
    November 17, 2005
    Hi Imi!

    It's always nice to see your comments :).

  • Anonymous
    February 07, 2006
    I was reading today an internal distribution list and I saw an interesting thread about autonumbered...

  • Anonymous
    July 11, 2006
    For some reason the indentation formatting won't work for me.  I have an XML file called GGData that I want to format.  I have the following lines of code:

    Dim doc As New XmlDocument()
    Dim writer As New XmlTextWriter("GGData.xml", Nothing)
    writer.Formatting = Formatting.Indented
    doc.Save(writer)

    The above overwrites my GGData.xml file with a blank file of 0 bytes.

  • Anonymous
    November 22, 2006
    Hi Erika Have you ever done the above indenting on the output of SQL Server "for xml"? cheers /s

  • Anonymous
    March 12, 2007
    The comment has been removed

  • Anonymous
    May 22, 2007
    Do you have any tips related to simplifying WordML(2003) documents?   The back story: I receive documents to be converted to pdf from the legal department in Word format (2003) and when I save the documents as pdfs the documents are often very disjointed I think because legal is tracking all the changes in the documents and to adequately track the changes it creates many nodes.  Can these documents be re-combined to be simplified again?

  • Anonymous
    June 11, 2007
    i want to fetch from Text File in connectivity from VB.NET into XML. Text File must be UNICODE IF U have any code for related to it's topic plz sent me my email-id : www.chaudhary_aparna20@yahoo.co.in plz send meeeeeeeeeeeeeeeeee

  • Anonymous
    October 12, 2007
    The comment has been removed

  • Anonymous
    October 26, 2007
    If you want it in a TextBox I assume you'd need to put the formated xml in a string.  Here's how I did it. public static string FormatXml(XmlDocument doc) { XmlTextWriter xmlWriter; StringWriter textWriter; // Format the Xml document with indentation and save it to a string. textWriter = new StringWriter(); xmlWriter = new XmlTextWriter(textWriter); xmlWriter.Formatting = Formatting.Indented; doc.Save(xmlWriter); return textWriter.ToString(); }

  • Anonymous
    November 07, 2007
    Works perfect. Thank you for this simple but accurate snippet!

  • Anonymous
    June 05, 2008
    Thanks for the indent code. It worked very well.

  • Anonymous
    August 02, 2008
    And for using tab as indentation char, additionally set: l_XMLWriter.IndentChar = 't'; l_XMLWriter.Indentation = 1; before l_XMLDoc.Save(l_XMLWriter);

  • Anonymous
    August 26, 2008
    &lt;p&gt;The following is an example of extracting correctly indented XML from an Xml document...&lt;/p&gt; ...

  • Anonymous
    October 23, 2008
    The comment has been removed

  • Anonymous
    November 02, 2008
    xmlindenter: I'm having exactly the same problem, and i haven't yet figured it out. It would be nice if someone could guide us.

  • Anonymous
    November 17, 2008
    Thanks msdn@chasmer.com Yours is the best on the internet :-)

  • Anonymous
    November 27, 2008
    Can anybody tell me what is the name of the file to change this? <?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"/>

  • Anonymous
    February 10, 2009
    Thanks - this piece was REALLY USEFULL!! XmlTextWriter writer = new XmlTextWriter("data.xml",null); writer.Formatting = Formatting.Indented;

  • Anonymous
    April 21, 2009
    Like Sexton said: Have you ever done the above indenting on the output of SQL Server "for xml"?

  • Anonymous
    June 18, 2009
    Make sure you close the XmlTextWriter after you're done with it otherwise you'll leave file handles open!! writer.Close();

  • Anonymous
    August 27, 2009
    There are problems in .NET's implementation. For instance, if you modify a node by assigning its InnerXml and then save the XML immediately, it will retain the indenting (if any) in the string you assigned to InnerXml, no matter how you set PreserveWhiteSpace or Formatting or whatever. If you work on the XmlDocument later, inserting, modifying nodes, the indenting will return to normal but not if you save immediately.

  • Anonymous
    January 27, 2010
    private static string FormatXml(XmlDocument doc) { string rtn = string.Empty; using (StringWriter textWriter = new StringWriter()) { using (XmlTextWriter xmlWriter = new XmlTextWriter(textWriter)) { xmlWriter.Formatting = Formatting.Indented; doc.Save(xmlWriter); } rtn =textWriter.ToString(); } return rtn; }

  • Anonymous
    January 27, 2010
    The comment has been removed

  • Anonymous
    February 17, 2011
           private static string IndentXMLString(String xml)        {            try            {                // Cargo el XML sin formato                XmlDocument xmldoc = new XmlDocument();                xmldoc.LoadXml(xml);                // Configuro el formato                XmlWriterSettings settings = new XmlWriterSettings();                settings.Indent = true;                settings.IndentChars = "t";                settings.OmitXmlDeclaration = true;                settings.NewLineOnAttributes = false;                // Formateo y retorno                StringBuilder output = new StringBuilder();                XmlWriter writer = XmlWriter.Create(output, settings);                xmldoc.WriteContentTo(writer);                writer.Flush();                return output.ToString();            }            catch (Exception ex)            {                MessageBox.Show(ex.ToString());            }            return "";        }

  • Anonymous
    February 25, 2012
    If you want to indent online : http://www.indentation-xml.com