Format an XML file so it looks nice in C#


This example shows how to format an XML file. When the computer processes an XML file, it doesn’t care about formatting. It doesn’t need indentation and new lines to make the file look nice. As long as the file is properly constructed, the file can be run all together in one long line as in:


Formatting an XML document for human consumption isn’t hard, but it is confusing. The following code assumes you have created an XML document object as described in the example Use objects to make an XML document in C#. The following code formats and displays the object’s XML text.

// Format the XML text.
StringWriter string_writer = new StringWriter();
XmlTextWriter xml_text_writer = new XmlTextWriter(string_writer);
xml_text_writer.Formatting = Formatting.Indented;

// Display the result.
txtResult.Text = string_writer.ToString();

This code creates a StringWriter and an XmlTextWriter associated with it. It sets the XmlTextWriter‘s properties so it formats the XML code with indentation and then calls the XML document object’s WriteTo method to write the document’s XML code into the XmlTextWriter (which writes it into the StringWriter). Finally, the code displays the text contained in the StringWriter.

The following text shows the result.


Download Example   Follow me on Twitter   RSS feed

This entry was posted in strings, XML and tagged , , , , , , , , , , . Bookmark the permalink.

6 Responses to Format an XML file so it looks nice in C#

  1. Arutyun Enfendzhyan says:

    Just use XDocument to format xml in one line. Don’t forget to use: using System.Linq;
    var xml_formatted = XDocument.Parse (xml_not_formatted).ToString ();

    • AndrĂ© R says:

      XDocument has some limitations though.
      XDocument loads the whole document into RAM. When the document is several GB big, 32 bit systems will inevitably reach their limits.
      The solution above also works for big documents

    • RodStephens says:

      Well, this example displays the XML as text with indentation. If the file is too big, you are going to have problems no matter what.

  2. the computer says:

    xml_document : missing type

Comments are closed.