This is a small piece of code I’m using to make the layout of an XML string a bit prettier.

It’s very useful if you want to write some XML to a text file that will be edited later.

protected string PrettyPrintXml(string xmlString)
{
    XmlDocument xmlDoc = new XmlDocument();
    StringWriter stringWriter = new StringWriter();
    XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter);
    xmlWriter.Formatting = Formatting.Indented;
    xmlDoc.LoadXml(xmlString);
    xmlDoc.WriteContentTo(xmlWriter);
    return stringWriter.ToString();
}

Leave a Reply