Welcome to MSDN Blogs Sign in | Join | Help

Pretty-printing valid xml snippet

It's proven useful in a couple of places, and it's pretty small and self-documenting.  I had written this mainly to look at my VS settings file in a nicer way since it saves with a minimum of whitespace.

 

private static string ToPrettyXml(string xml)

{

    XmlDocument doc = new XmlDocument();

    try

    {

        doc.LoadXml(xml);

    }

    catch (XmlException)

    {

        return xml;

    }

 

    using (StringWriter sw = new StringWriter())

    {

        using (XmlTextWriter xmlWriter = new XmlTextWriter(sw))

        {

            xmlWriter.Formatting = Formatting.Indented;

            doc.WriteContentTo(xmlWriter);

        }

        return sw.ToString();

    }

}

 

Published Saturday, December 11, 2004 12:50 PM by jmanning

Comments

# re: Pretty-printing valid xml snippet

Saturday, December 11, 2004 11:16 PM by Uwe Keim
Nice function. I must look at that Formatting property in more detail, I guess... :-)
Anonymous comments are disabled
 
Page view tracker