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.

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

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.