Skip to content

Instantly share code, notes, and snippets.

@robfe
Created March 4, 2011 17:37
Show Gist options
  • Save robfe/855332 to your computer and use it in GitHub Desktop.
Save robfe/855332 to your computer and use it in GitHub Desktop.
Method to compress XAML: Removes comments, whitespace, and mc:Ignorable components
static string Minimize(XDocument document)
{
//take out the comments
document.DescendantNodes().OfType<XComment>().Remove();
//take out the mc:ignorables
XNamespace mc = "http://schemas.openxmlformats.org/markup-compatibility/2006";
var ignorable = document.Root.Attribute(mc + "Ignorable");
if (ignorable != null)
{
string[] ignorablePrefixes = ignorable.Value.Split(' ');
var prefixNamespaces = document
.Root
.Attributes()
.Where(a => a.IsNamespaceDeclaration)
.GroupBy(a => a.Name.Namespace == XNamespace.None ? String.Empty : a.Name.LocalName, a => XNamespace.Get(a.Value))
.ToDictionary(g => g.Key, g => g.First());
List<string> ignorableNamespaces = ignorablePrefixes.Select(x => prefixNamespaces[x].NamespaceName).ToList();
//remove elements
document.Descendants()
.Where(x => ignorableNamespaces.Contains(x.Name.NamespaceName))
.Remove();
//remove attributes
document.Descendants()
.SelectMany(x => x.Attributes())
.OfType<XAttribute>()
.Where(x => ignorableNamespaces.Contains(x.Name.NamespaceName))
.Remove();
}
//create the tightest XmlWriterSettings imaginable
var settings = new XmlWriterSettings
{
NamespaceHandling = NamespaceHandling.OmitDuplicates,
Indent = false,
NewLineChars = "",
NewLineHandling = NewLineHandling.Replace,
};
//save it into a stringbuilder
StringBuilder output = new StringBuilder();
var writer = XmlWriter.Create(output, settings);
document.Save(writer);
writer.Flush();
//get rid of the silly space at the end of all self-closing tags
output.Replace("\" />", "\"/>");
return output.ToString();
}
@EdWatts
Copy link

EdWatts commented Jan 6, 2012

Very handy!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment