sravan kumar
sravan kumar

Reputation: 613

XSLT to check if a xml element exist else skip the parent element

I have been trying to skip a particular parent element if a child element doesn't exist.Am new to XSLT mapping. Please correct me if I am going wrong somewhere.

Below is xml I have

<element1>
    <element2>
        <element3>
            <data1>aaaa</data1>
            <data2>bbbb</data2>
            <element4>
                <data3>cccc</data3>
                <data4>dddd</data4>
            </element4>
        </element3>
    </element2>
    <element2>
        <element3>
            <data1>eeee</data1>
            <data2>ffff</data2>
        </element3>
    </element2>
</element1>

I want to check if element 4 exists else I would like to skip element 2 completely.

Expected result is

<element1>
    <element2>
        <element3>
            <data1>aaaa</data1>
            <data2>bbbb</data2>
            <element4>
                <data3>cccc</data3>
                <data4>dddd</data4>
            </element4>
        </element3>
    </element2>
</element1>

I have been trying with below xsl:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema">
 <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="/element1/element2[element3/element4 = '']"/>

</xsl:stylesheet>

Upvotes: 0

Views: 600

Answers (1)

Tim C
Tim C

Reputation: 70648

Your current template match will only match an element2 if an element3/element4 exists and its value is an empty string. That is to say, it would match this...

<element2>
    <element3>
        <element4 />
    </element3>
</element2>

To check for the existence (or non-existence), what you need to do is this....

<xsl:template match="/element1/element2[not(element3/element4)]"/>

Upvotes: 2

Related Questions