Make XML More Readable
Use the XmlTextWriter class to format XML nicely with a minimal amount of work.
by Dan Wahlin
Posted April 14, 2003
One of the many benefits of XML is its ability to be read by both humans and computers. XML developers can open an XML document in a program as simple as Notepad and edit data as appropriate. Although computers can easily work with XML documents that are not indented and formatted nicely, this can present more of a problem for humans. Take this XML document as an example:
<customers><customer
id='2'><fname>John</fname><lname
>Doe</lname><addressInfo><street
>1234 Anywhere
St.</street><city>Phoenix</city>
<zip>12345</zip></addressInfo>
</customer></customers>
When you need to format XML to make it more readable, you can use the .NET platform's XmlTextWriter class to accomplish the task with a minimal amount of work.
Indenting XML document hierarchies so they're easier to read is made possible through the XmlTextWriter's Formatting and Indentation properties. You simply set the Formatting property to an enumeration value of Formatting.Indented, and the Indentation property to a value representing the number of spaces that should be used for indentation. If no value is assigned to the Indentation property, a default value of 2 is used (the default indentation character is a space, but you can change this through the IndentChar property).
Here's a simple example of formatting data loaded into an XmlDocument object instance using the XmlTextWriter. After loading the data into the DOM, the XmlDocument class's WriteTo() method is called to write the data directly to an XmlTextWriter instance:
string filePath =
@"c:\xmlDocuments\customers.xml";
XmlTextWriter writer = new
XmlTextWriter(filePath,Encoding.UTF8);
writer.Formatting = Formatting.Indented;
writer.Indentation = 4;
XmlDocument doc = new XmlDocument();
doc.LoadXml(@"<customers><customer
id='2'><fname>John</fname><lname
>Doe</lname><addressInfo><street
>1234 Anywhere
St.</street><city>Phoenix</city>
<zip>12345</zip></addressInfo>
</customer></customers>");
doc.WriteTo(writer);
writer.Close();
Here's the output document generated by that C# code:
<customers>
<customer id="2">
<fname>John</fname>
<lname>Doe</lname>
<addressInfo>
<street>1234 Anywhere St.</street>
<city>Phoenix</city>
<zip>12345</zip>
</addressInfo>
</customer>
</customers>
Visit the XML for ASP.NET Developers site for a showing how to modify the indentation in an XML document using the XmlTextWriter class.
About the Author
Dan Wahlin authored (Sams) and founded Wahlin Consulting, which focuses on XML and Web Service consulting and training. Dan also operates the XML for ASP.NET Developers Web site: . Find more information at .
Back to top
|