Skip to content

Instantly share code, notes, and snippets.

@swilliams
Created December 22, 2010 16:22
Show Gist options
  • Save swilliams/751708 to your computer and use it in GitHub Desktop.
Save swilliams/751708 to your computer and use it in GitHub Desktop.
Formats XML to be prettily indented. Useful for dealing with XML saved from the Internet.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
// Compile and run via the command line:
// > XmlFormatter.exe < BadXml.xml > GoodXml.xml
// If GoodXml is ignored, it will print to stdout.
namespace XmlFormatter {
class Program {
static void Main(string[] args) {
var tr = Console.In;
string s = tr.ReadToEnd();
XmlDocument doc = new XmlDocument();
try {
doc.LoadXml(s);
StringBuilder sb = new StringBuilder();
using (XmlTextWriter tw = new XmlTextWriter(new StringWriter(sb))) {
tw.Formatting = Formatting.Indented;
doc.Save(tw);
}
Console.Write(sb.ToString());
} catch (XmlException ex) {
Console.WriteLine("There was an error reading the XML file. Please make sure it is an actual XML file. " + ex.Message);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment