Obtaining Indented XML as a String

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(); } }

10 thoughts on “Obtaining Indented XML as a String

  1. 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!

Leave a Reply

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