[xml] XSL if: test with multiple test conditions

[Solved]

Thanks to @IanRoberts, I had to use the normalize-space function on my nodes to check if they were empty.

<xsl:if test="((node/ABC!='') and (normalize-space(node/DEF)='') and (normalize-space(node/GHI)=''))">
  This worked perfectly fine.
</xsl:if>

[Problem]

I am trying to create a xsl condition to check if combinations of node are empty or not. I have tried below conditions but they do not work, does anyone have an idea as to how to get it working

<xsl:if test=" node/ABC!='' and node/DEF='' and node/GHI='' ">
This does not work
</xsl:if>

I have also tried

<xsl:when test="((node/ABC!='') and (node/DEF='') and (node/GHI=''))">
This does not work either..
</xsl:when>

And also tried

<xsl:if test="(node/ABC!='')>
<xsl:if test="(node/DEF='')>
<xsl:if test="(node/GHI='')">
Nope not working..
</xsl:if>
</xsl:if>
</xsl:if>

I, then tried with single xsl:if conditions, and below is the observation

<xsl:if test="node/ABC!=''>
**This is working fine**
</xsl:if>

However if i try to search for empty condition, i.e

<xsl:if test="node/ABC=''>
**This does not work**
</xsl:if>

Also, if i try with a == (double equal to), then it gives xslt error. i.e

<xsl:if test="node/ABC==''>
***This gives a compilation error***
</xsl:if>

I would like help in figuring out how to get my xsl:if test working to check for multiple conditions. Thanks in advance.

[Edit] : Just to update here that the if condition where all the nodes are not empty works, it does not work when i try to check for any other node out of the three nodes that are empty.

For eg :

<xsl:if test=" node/ABC!='' and node/DEF!='' and node/GHI!='' ">
This condition works perfectly fine.
</xsl:if>

This question is related to xml xslt

The answer is


Try to use the empty() function:

<xsl:if test="empty(node/ABC/node()) and empty(node/DEF/node())">
    <xsl:text>This should work</xsl:text>
</xsl:if>

This identifies ABC and DEF as empty in the sense that they do not have any child nodes (no elements, no text nodes, no processing instructions, no comments).

But, as pointed out by @Ian, your elements might not be empty really or that might not be your actual problem - you did not show what your input XML looks like.

Another cause of error could be your relative position in the tree. This way of testing conditions only works if the surrounding template matches the parent element of node or if you iterate over the parent element of node.


Just for completeness and those unaware XSL 1 has choose for multiple conditions.

<xsl:choose>
 <xsl:when test="expression">
  ... some output ...
 </xsl:when>
 <xsl:when test="another-expression">
  ... some output ...
 </xsl:when>
 <xsl:otherwise>
   ... some output ....
 </xsl:otherwise>
</xsl:choose>