Top

Tags


Roadkill .NET Wiki

Google ads

Recommended reading


Search

Wednesday
Sep092009

Formatting XML in C# 

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

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>
« IComparable, IComparer, Equals, IEquatable<T>, IEqualityComparer | Main | A Look At .NET ORMs - Part 1 »