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="">
<xsl:output omit-xml-declaration="no" indent="no"/>
<xsl:strip-space elements="*" />
<xsl:template match="*[not(node()) and not(./@*)]"/>
<xsl:template match="@* | node()">
<xsl:apply-templates select="@* | node()"/>

And some code...

//Xsl to strip stylesheet
string strippingStylesheet = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><xsl:stylesheet version=\"1.0\" xmlns:xsl=\"\"><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();

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

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

//Reload source with emptied nodes

No comments: