Reputation: 25
I'm trying to exclude record nodes if all but one element () are empty. For simplicity's sake, I've reduced the number of elements beneath the record element to four but it's possible for me to have up to 50. (So the inverse logic of checking if every field = ''
would be horrible.)
Input
<root>
<record>
<date>1/1/2015</date>
<text>not empty</text>
<text1/>
<text2>not empty</text2>
</record>
<record>
<date>1/3/2015</date>
<text/>
<text1/>
<text2/>
</record>
<record>
<date>1/5/2015</date>
<text/>
<text1/>
<text2>more not empty</text2>
</record>
The closest I've come is the following
<!--Identity template to copy all content by default-->
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="record/*[not(node())]"/>
<xsl:template match="date[not(following-sibling::* != '')]"/>
Output
<root>
<record>
<date>1/1/2015</date>
<text>not empty</text>
<text2>not empty</text2>
</record>
<record/>
<record>
<date>1/5/2015</date>
<text2>more not empty</text2>
</record>
</root>
I would like to exclude the empty <record/>
. This also doesn't work if I have a second 'known' element. For example, if there was a <date2>1/1/99</date2>
below the first date element on every record. Anyone have any ideas?
Upvotes: 1
Views: 271
Reputation: 116992
I'm trying to exclude record nodes if all but one element () are empty.
How about counting how many are not empty?
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<!-- identity transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="record[count(*[node()]) < 2]"/>
<xsl:template match="record/*[not(node())]"/>
</xsl:stylesheet>
Alternatively, if you only want to look at "unknown" nodes:
<xsl:template match="record[not(*[not(self::date or self::date1)][node()])]"/>
This suppresses any record where all fields that are not date
or date1
are empty.
Upvotes: 1