Skip to content

Instantly share code, notes, and snippets.

@justinAurand
Last active December 25, 2015 19:59
Show Gist options
  • Save justinAurand/7031711 to your computer and use it in GitHub Desktop.
Save justinAurand/7031711 to your computer and use it in GitHub Desktop.
Format a document XML for readability.
using System.IO;
using System.Text;
using System.Xml;
class IndentXml
{
public static void Main()
{
var xmlDocument = new XmlDocument();
xmlDocument.Load(@"C:\Original.xml");
// NOTE: This causes XML to have an attribute of UTF-16 encoding. You may need to change this manually.
var xmlContents = xmlDocument.Indent();
File.WriteAllText(@"C:\Formatted.xml", xmlContents);
}
}
static class XmlDocumentExtension
{
public static string Indent(this XmlDocument xml)
{
var xmlWriterSettings = new XmlWriterSettings
{
Indent = true,
IndentChars = "\t",
NewLineChars = "\r\n",
NewLineHandling = NewLineHandling.Replace
};
var stringBuilder = new StringBuilder();
using (var xmlWriter = XmlWriter.Create(stringBuilder, xmlWriterSettings))
xml.Save(xmlWriter);
return stringBuilder.ToString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment