With many developers working together, formatting styles can sometimes be an issue. This is most noticeable when working with XAML files, and the biggest culprit for formatting issues is poor tabbing and inconsistent tab characters. Luckily there is an easy way to standardize XAML formatting through that implantation of a custom check-in policy that can programmatically fix all XAML files prior to being checked in.
Using XmlWriter in conjunction with the XmlWriterSettings class we can easily customize our output . The XmlWriterSettings properties give us a lot of control as to how we want the XML or XAML to look and our settings are documented and are worth looking over. I am also using XmlReader and XmlReaderSettings to convert the text into an XmlDocument, were the XmlReaderSettings class is used to ensure that we ignore any potentially invalid XML characters in our XAML . I encountered one tricky bit were the XmlReader will break on decimal and hex character reference, this was solved by doing a text replace on all “&” with “&” pre-XmlReader and converting back post-XmlWriter.
public static class Tabify
// Tabify XML document
public static void Xml(string filename)
// Tabify Xaml document
public static void Xaml(string filename)
private static void DoTabify(string filename, bool xaml=false)
// XmlDocument container
XmlDocument xmlDocument = new XmlDocument();
// We want to make sure that decimal and hex character references are not lost
string xmlString = File.ReadAllText(filename);
xmlString = xmlString.Replace("&", "&");
// Xml Reader settings
XmlReaderSettings xmlReadSettings = new XmlReaderSettings()
CheckCharacters = false, // We have some invalid characters we want to ignore
// Use XML reader to load content to XmlDocument container
using (XmlReader xmReader = XmlReader.Create(new StringReader(xmlString), xmlReadSettings))
// Customize how our XML will look, we want tabs, UTF8 encoding and new line on attributes
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings()
Indent = true, // Indent elements
IndentChars = "\t", // Indent with tabs
CheckCharacters = false, // Ignore invalid characters
NewLineChars = Environment.NewLine, // Set newline character
NewLineHandling = NewLineHandling.None, // Normalize line breaks
Encoding = new UTF8Encoding() // UTF8 encoding
// We do not want the xml declaration for xaml files
xmlWriterSettings.OmitXmlDeclaration = true; // For XAML this must be false!!!!
StringBuilder xmlStringBuilder = new StringBuilder();
// Write xml to file using saved settings
using (XmlWriter xmlWriter = XmlWriter.Create(xmlStringBuilder, xmlWriterSettings))
// Restore decimal and hex character references
xmlString = xmlStringBuilder.ToString().Replace("&", "&");
 XmlWriter Class. MSDN Library.
 XmlWriterSettings Class. MSDN Library.
 XmlReader ClassXmlReader Class. MSDN Library.
 XmlReaderSettings Class. MSDN Library.
 XmlDocument Class. MSDN Library.
 Parsing Xml with Invalid Characters in C#. Paul Selles