Format an XML file so it looks nice in C#

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>And
ers</LastName><EmployeeId>11111</EmployeeId></Employee><Employe
e><FirstName>Betty</FirstName><LastName>Beach</LastName><Employ
eeId>22222</EmployeeId></Employee><Employee><FirstName>Chuck</F
irstName><LastName>Cinder</LastName><EmployeeId>33333</Employee
Id></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.

// 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 properly and then calls the XML document object's WriteTo method to write into the XmlTextWriter (which writes into the StringWriter). Finally it displays the text 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>

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.