开发者

XML Minify in .NET

开发者 https://www.devze.com 2022-12-10 23:03 出处:网络
I\'d like to read in the following XML: <node></node> And then wr开发者_StackOverflow中文版ite it out, minified, like this:

I'd like to read in the following XML:

<node></node>

And then wr开发者_StackOverflow中文版ite it out, minified, like this:

<node/>

Obviously this has the same meaning, but the second file is smaller for sending across the wire.

I'm trying to find a way to do this in .NET. I can't seem to find an option or setting that would drop unnecessary closing tags.

Suggestions?


You can copy the XML into a new structure.

public static XElement Minify(XElement element) {
    return new XElement(element.Name, element.Attributes(),
        element.Nodes().Select(node => {
            if (node is XElement)
                return Minify((XElement)node);
            return node;
        })
    );
}

Here is another solution but LINQ-less http://social.msdn.microsoft.com/Forums/en-US/xmlandnetfx/thread/e1e881db-6547-42c4-b379-df5885f779be

XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.Load("input.xml");
foreach (XmlElement el in 
   doc.SelectNodes("descendant::*[not(*) and not(normalize-space())]"))
{
  el.IsEmpty = true;
}
doc.Save("output.xml");


If you use LINQ to XML, you can call XElement.RemoveNodes() which will convert it to the second form. So something like this:

var emptyTags = doc.Descendants().Where(x => !x.Nodes().Any()).ToList();

foreach (XElement tag in emptyTags)
{
    tag.RemoveNodes();
}

Then save the document in the normal way, and I think it will do what you want...


Take a look at the XmlElement IsEmpty property.


I didn't test this myself, but have you tried experimenting with the XmlWriter's XmlWriterSettings.OutputMethod Property?

The following page gives you the options you can use:

http://msdn.microsoft.com/en-us/library/system.xml.xmloutputmethod.aspx


Try a WebMarkupMin XML Minifier with the option "Collapse tags without content":

    const string xmlInput = "<row RoleId=\"4\" RoleName=\"Administrator\"></row>\n" +
        "<row RoleId=\"5\" RoleName=\"Contributor\"></row>\n" +
        "<row RoleId=\"6\" RoleName=\"Editor\"></row>"
        ;

    var xmlMinifier = new XmlMinifier(
        new XmlMinificationSettings{ CollapseTagsWithoutContent = true });

    MarkupMinificationResult result = xmlMinifier.Minify(xmlInput);

    Console.WriteLine("Minified content:{0}{0}{1}",
        Environment.NewLine, result.MinifiedContent);
0

精彩评论

暂无评论...
验证码 换一张
取 消