Obtaining Indented XML as a String

Published Tue, Jun 22 2004 0:55 | coad

Using XmlDocument.Save(string file) produces a file with nicely indented elements. XmlDocument.OuterXml returns a string without any formatting. If you want a nicely formatted string (to display to the user, write to console, etc), without directly writing to a file, you must use the XmlTextWriter.

The using statements in the method makes sure the resorces are disposed of sooner than later. Here is the code to return a string of formatted XML from an XmlDocument. Download Example Code (requires Visual Studio 2005)

using System.IO; using System.Xml; public static string FormatXML(XmlDocument doc) { // Create a stream buffer that can be read as a string using (StringWriter sw = new StringWriter()) // Create a specialized writer for XML code using (XmlTextWriter xtw = new XmlTextWriter(sw)) { // Set the writer to use indented (hierarchical) elements xtw.Formatting = System.Xml.Formatting.Indented; // Write the XML document to the stream doc.WriteTo(xtw); // Return the stream as a string return sw.ToString(); } }

Filed under: ,

Comments

# coad said on November 15, 2004 2:23 PM:

Worked like a champ for me. Thanks.

# coad said on January 10, 2005 3:57 AM:

it's very helpful to me thank you :)

# coad said on February 3, 2005 7:29 AM:

Just wanna say THANX... ;-)

# coad said on March 4, 2005 4:39 AM:

It saved a lot of person hour for us
Thank you very much

# coad said on March 17, 2005 2:54 PM:

Yo tambien quiero decir GRACIAS!!!!!

# Fredrik said on October 12, 2006 8:00 AM:

FINALLY! I've been looking for this kind of solution for 8 hours.

I am so happy right now.

Super great tutorial or what I sould call it.

Thank you!

# Noah Coad's Code said on February 21, 2007 1:32 PM:

I was digging around recently and came across an interesting fact... My blog gets more views per month

# Rashmi said on June 6, 2007 7:04 AM:

Finally you helped me out

# Jan said on July 18, 2007 3:53 AM:

At a glance, the example at msdn2.microsoft.com/.../t8t5yhhk.aspx seems to provide the similar functionality

# Bijay said on September 10, 2007 11:22 AM:

Works like a  charm . Thanks

# Moki said on October 19, 2007 9:10 AM:

The code snippet is very handy. Thanks for posting!