Search code examples
.netxmlminify

XML Minify in .NET


I'd like to read in the following XML:

<node></node>

And then write 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?


Solution

  • 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...