Chris's coding blog

Format XML in C#

September 09, 2009

Below is a small snippet showing how to format (or re-format) XML so it’s indented. XML isn’t stored in this humanly readable way in databases (or in System.XML’s various writers), so this method makes the XML easier on the eyes.

/// <summary>
/// Formats the provided XML so it's indented and humanly-readable.
/// </summary>
/// <param name="inputXml">The input XML to format.</param>
/// <returns></returns>
public static string FormatXml(string inputXml)
{
XmlDocument document = new XmlDocument();
document.Load(new StringReader(inputXml));
StringBuilder builder = new StringBuilder();
using (XmlTextWriter writer = new XmlTextWriter(new StringWriter(builder)))
{
writer.Formatting = Formatting.Indented;
document.Save(writer);
}
return builder.ToString();
}
view raw gistfile1.cs hosted with ❤ by GitHub

csharpxml

I'm Chris Small, a software engineer working in London. This is my tech blog. Find out more about me via GithubStackoverflowResume