Friday, 15 June 2007

How to remove all empty nodes from an XmlDocument in c#

I've used xsl before for stripping out unwanted empty nodes from passed xml - but now needed it for some c# code. So I created the following chunk of code and it works a treat.

This is the xslt which does all the hard work...


<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="no" indent="no"/>
<xsl:strip-space elements="*" />
<xsl:template match="*[not(node()) and not(./@*)]"/>
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>


And some code...

//Xsl to strip stylesheet
string strippingStylesheet = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"><xsl:output omit-xml-declaration=\"no\" indent=\"no\"/><xsl:strip-space elements=\"*\" /><xsl:template match=\"*[not(node()) and not(./@*)]\"/><xsl:template match=\"@* | node()\"><xsl:copy><xsl:apply-templates select=\"@* | node()\"/></xsl:copy></xsl:template></xsl:stylesheet>";

//Set up empty node stripper
XmlDocument stripper = new XmlDocument();
stripper.LoadXml(strippingStylesheet);

//Compile here
StringWriter output = new StringWriter();
XslCompiledTransform emptyNodeRemover = new XslCompiledTransform();
emptyNodeRemover.Load(stripper);

//Port output to string
StringWriter output = new StringWriter();
emptyNodeRemover.Transform(new XmlNodeReader(source), null, output);
output.Flush();

//Reload source with emptied nodes
source.LoadXml(output.ToString());
output.Close();
output.Dispose();

No comments: