Contents

1.0 - Introduction
2.0 - Indenting XML
3.0 - Summary
4.0 - Notes/Links


Download source code (Visual C# Express 2010): Solution_XMLIndent_01.zip [119 kB].
Download test files (XML): Testfiles_XMLIndent_01.zip [1 kB].


1.0 - Introduction

XML code without indentation is written to a single line. It is efficient because the file contains a minimum of characters, but it is badly readable. When XML is inspected visually or edited by hand, it is better to present the XML as tree. Indented code as input for a validator also makes returned error messages better readable, because it uses line and column numbers to indicate the position of detected errors.



Indentations.


Indentation is realized by adding returns and whitespace in the markup. Doing so by hand is time-consuming, even for small files, so a function is made for adding or removing indentation to XML code quickly.


2.0 - Indenting XML

A straightforward way to make indented XML is to use the XmlWriter.Create method with XmlWriterSettings as one of the parameters [1][2]. Property XmlWriterSettings.Indent is set to true and property XmlWriterSettings.IndentChars to the string of characters to indent the markup, for example a number of spaces or a tab "\t".



Fig.2.1 - A switch on the save-function determines if the output XML is indented or not.


The following function is an implementation. It has an XDocument as input and the XML from it is saved to file with- or without indentation, set with an additional parameter.


  XML - Save an XML document to file.

  // ---------------------------------------------------------------
  // Date      100512
  // Purpose   Save an XML document to file.
  // Entry     sFileName - The name of the XML file.
  //           xDox - The XML document to save.
  //           indent - true: indent the XML.
  // Return    An empyt string if successful.
  // Comments  
  // ---------------------------------------------------------------
  private string SaveXML(string sFileName, XDocument xmlDoc, bool indent)
  {
      string sErr = "";
      try
      {
          XmlWriterSettings settings = new XmlWriterSettings();
          settings.Indent = indent;
          settings.IndentChars = "    ";
          using (XmlWriter xWriter = XmlWriter.Create(sFileName, settings))
          {
              xmlDoc.Save(xWriter);
          }
          sErr = "";
      }
      catch (Exception ex)
      {
          sErr = ex.Message;
      }
      return sErr;
  }


Another function is made for opening the XML file, an XDocument is returned from it.


  C# - Open an XML document from file.

  using.System;
  using System.Xml;
  using System.Xml.Linq;

  // ---------------------------------------------------------------
  // Date      100512
  // Purpose   Open an XML file.
  // Entry     sFileName - The name of the XML file.
  // Return    The XML document.
  // Comments  
  // ---------------------------------------------------------------
  private XDocument OpenXML(string sFileName)
  {
      try
      {
          return XDocument.Load(sFileName);
      }
      catch
      {
          return null;
      }
  }


By combining the two functions XML is converted into an indented or unindented version. The intermediate xDocument object can be edited with LINQ optionally.


  C# - How to use OpenXML() and SaveXML().

  // Open un-indented file.
  xDocument xDoc = OpenXML(D:\Testfiles\"List_01a.xml");
  // Save as indented.
  SaveXML(D:\Testfiles\"List_01b.xml", xDoc, true);


Result:


  XML - Input (List_01a.xml)

 <?xml version="1.0" encoding="utf-8"?><data><list id="L0"><li>Item_00</li><li> ...



  XML - Output (List_01b.xml). Line numbers added by hand.

 01 <?xml version="1.0" encoding="utf-8"?>
 02 <data>
 03     <list id="L0">
 04         <li>Item_00</li>
 05         <li>Item_01</li>
 06         <li>Item_02</li>
 07         <list id="L1">
 08             <li>Item_10</li>
 09             <li>Item_11</li>
 10             <li>Item_12</li>
 11             <li>Item_13</li>
 12         </list>
 13         <li>Item_03</li>
 14     </list>
 15 </data>


Testing this code on well-formedness, with the tag on line 12 is <list> instead of </list>, a validator returns for List_01a.xml:

The 'list' start tag on line 1 position 108 does not match the end tag of 'data'. Line 1, position 216.

When code on long lines is wrapped to the width of the text-area inside an editor, it is difficult to find column 108.

The same validator returns for List_01b.xml:

The 'list' start tag on line 7 position 10 does not match the end tag of 'data'. Line 15, position 3.

That is a more useful result. Adding indentation gives a slightly larger file, but it can save much time searching for errors. When a unindented version of the file is still needed function SaveXML() can be used with the third parameter set to 'false'.


3.0 - Summary

A function is made for indenting or unindenting XML code from file. Indented XML is better readable for humans and validators.



 


4.0 - Notes/Links


[1] MSDN - XmlWriter Class.
Represents a writer that provides a fast, non-cached, forward-only means of generating streams or files containing XML data.
http://msdn.microsoft.com/en-us/library/system.xml.xmlwriter.aspx

[2] MSDN - XmlWriterSettings Class.
Specifies a set of features to support on the XmlWriter object created by the XmlWriter.Create method.
http://msdn.microsoft.com/en-us/library/system.xml.xmlwritersettings.aspx