Created
March 4, 2011 17:37
-
-
Save robfe/855332 to your computer and use it in GitHub Desktop.
Method to compress XAML: Removes comments, whitespace, and mc:Ignorable components
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
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(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very handy!