tags:

views:

117

answers:

4
+2  Q: 

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?

A: 

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

Jon Skeet
A: 

Take a look at the XmlElement IsEmpty property.

zac
IsEmpty will only tell me if the node has children or not. If I set it to true - it will drop child elements.
nikmd23
Don't set it to true for nodes that contain children, but if you set it to true for empty nodes then they would be serialized using the short format.
zac
so:if (x.IsEmpty) x.IsEmpty = true;? that seems a bit wrong.
nikmd23
Looks like Bob found something that uses this property in that way.
zac
+1  A: 

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");
Bob
A: 

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

David Stratton
I don't think that this will help, unless "Serialize according to the XML 1.0 rules." means to drop the empty end tags. I will try this out as an example though.
nikmd23