Outputting XML in a Visually Pleasing Manner

Published 16 October 03 02:11 PM | Scott Mitchell

Another XML challenge: given an XML string, like:

<book><title>1984</title><author>Orwell</author></book>

What's the easiest way to display the XML in a friendly, indented way, like:

<book>
<title>
1984
</title>
<author>
Orwell
</author>
</book>

Here is my approach, let me know if you know of one better. Essentially, what I do is the following:

  1. Populate an XmlDocument with the XML data.
  2. Create an XmlTextWriter instance that writes to a StringWriter and set its Formatting property to Formatting.Indented
  3. Save the XmlDocument's data to the XmlTextWriter via the Save() method
  4. Get the prettily formatted XML by calling the StringWriter's ToString() method.

Is there a more efficient way? It seems rather unfortunate to have to load the entire XML in an XmlDocument instance first. I guess one could use an XmlTextReader to read through each node, and then write it to the XmlTextWriter, but I don't see a method that does this for me automatically. Anywho, here's the code I use:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);

StringWriter sw = new StringWriter();
XmlTextWriter writer = new XmlTextWriter(sw);
writer.Formatting = Formatting.Indented;

xmlDoc.Save(writer);
Console.WriteLine(sw.ToString());

Filed under:

Comments

No Comments

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Archives

My Books

  • Teach Yourself ASP.NET 4 in 24 Hours
  • Teach Yourself ASP.NET 3.5 in 24 Hours
  • Teach Yourself ASP.NET 2.0 in 24 Hours
  • ASP.NET Data Web Controls Kick Start
  • ASP.NET: Tips, Tutorials, and Code
  • Designing Active Server Pages
  • Teach Yourself Active Server Pages 3.0 in 21 Days

I am a Microsoft MVP for ASP.NET.

I am an ASPInsider.