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();
}
}
Comments
- Anonymous
December 11, 2004
Nice function. I must look at that Formatting property in more detail, I guess... :-)