Format an XML file so it looks nice in C#

example

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:

<Employees><Employee><FirstName>Albert</FirstName><LastName>Anders</LastName><EmployeeId>11111</EmployeeId></Employee><Employee><FirstName>Betty</FirstName><LastName>Beach</LastName><EmployeeId>22222</EmployeeId></Employee><Employee><FirstName>Chuck</FirstName><LastName>Cinder</LastName><EmployeeId>33333</EmployeeId></Employee></Employees>

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;
xml_document.WriteTo(xml_text_writer);

// 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.

<Employees>
  <Employee>
    <FirstName>Albert</FirstName>
    <LastName>Anders</LastName>
    <EmployeeId>11111</EmployeeId>
  </Employee>
  <Employee>
    <FirstName>Betty</FirstName>
    <LastName>Beach</LastName>
    <EmployeeId>22222</EmployeeId>
  </Employee>
  <Employee>
    <FirstName>Chuck</FirstName>
    <LastName>Cinder</LastName>
    <EmployeeId>33333</EmployeeId>
  </Employee>
</Employees>


Download Example   Follow me on Twitter   RSS feed




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

Leave a Reply

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