XSLT To remove empty nodes and nodes with -1

I am not an XSLT master.

I have the current XSLT that I use to remove empty nodes:

string strippingStylesheet = "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">" + "<xsl:template match=\"@*|node()\">" + "<xsl:if test=\". != ''\">" + "<xsl:copy>" + "<xsl:apply-templates select=\"@*|node()\"/>" + "</xsl:copy>" + "</xsl:if></xsl:template></xsl:stylesheet>"; 

I need to find a way to also remove nodes with -1 in them. The previous developer thought that it would be nice to make each int in the system default to -1, and yes, this means that all database fields have -1 in them, and not null.

Since I want to defeat a dead horse (with a stick, a bat, a bazooka), I need to get back to work and do it.

Any help would be great.

+7
xml xslt
source share
2 answers

I have the current XSLT, which I use to remove empty nodes:

. ,,,,.

I need to find a way to also remove nodes with -1 in them

I assume that you want to remove all the "empty nodes".

Processing depends on the definition of "empty node". One reasonable definition in your case: Any element that has no attributes and children, or has no attributes, and has only one child, which is node text with a value of -1 .

Here is a simple solution for this definition.

This conversion is :

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

when applying the sample to this XML document :

 <t> <a>-1</a> <a>2</a> <b><c/></b> <d>-1</d> <d>15</d> <ex="1"/> <f>foo</f> </t> 

creates the desired, correct result :

 <t> <a>2</a> <b/> <d>15</d> <ex="1"/> <f>foo</f> </t> 
+12
source share

In a simple case, this should work:

 <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="*[. = '' or . = '-1']"/> 

With this simple input:

 <root> <node></node> <node>-1</node> <node>2</node> <node>8</node> <node>abc</node> <node>-1</node> <node></node> <node>99</node> </root> 

The result will be:

 <root> <node>2</node> <node>8</node> <node>abc</node> <node>99</node> </root> 
+5
source share

All Articles