Last active
December 25, 2015 19:59
-
-
Save justinAurand/7031711 to your computer and use it in GitHub Desktop.
Format a document XML for readability.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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