How to check if variable is Null or empty in XSLT?

Oleg_08 picture Oleg_08 · Mar 16, 2017 · Viewed 26.2k times · Source

I definded the following variables:

<xsl:variable name="pica036E"
                        select="recordData/record/datafield[@tag='036E']" />
<xsl:variable name="pica036F"
                        select="recordData/record/datafield[@tag='036F']" />

Now I need to do a condition if variable pica036E isn't empty and pica036F is empty show the following message otherwise show another message. That's my code, but I don't ge any output. Is "null or empty" correct defined?

<xsl:choose>
                        <xsl:when test="$pica036E != '' and $pica036F = ''">
                        <xsl:message>
                         036F no 036E yes      
                            </xsl:message>
                        </xsl:when>

                         <xsl:otherwise>
                        <xsl:message>
                                036E no 036F yes
                            </xsl:message>  
                        </xsl:otherwise> 
                    </xsl:choose>  

Answer

Michael Kay picture Michael Kay · Mar 16, 2017

In XPath, X=Y means (if some pair x in X, y in Y satisfy x = y), while X != Y means (if some pair x in X, y in Y satisfy x != y).

This means that if either X or Y is an empty sequence, then both X=Y and X!=Y are false.

For example, $pica036E != '' tests whether there is a value in $pica036E that is not a zero-length string. If there are no values in $pica036E then there is no value that satisfies this condition.

As a result, using != in XPath is always a code smell. Usually, rather than X != Y, you should be writing not(X = Y).