How to check if an element value is null using xsl:if

23,141

Solution 1

The following transformation should help you to handle all cases.

If the content of node1 is text, you can use text() to detect it. If the content is any element, you can use * to detect it. To check if it is empty, you can add the condition not(node()). If you want to do things if node1 itself is not present, add a not(node1) condition to the root node.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/rootNode/node1/text()">
has text
</xsl:template>
<xsl:template match="/rootNode/node1/*">
has elements
</xsl:template>
<xsl:template match="/rootNode/node1[not(node())]">
is empty
</xsl:template>
<xsl:template match="/rootNode[not(node1)]">
no node1
</xsl:template>
</xsl:stylesheet> 

You can apply the same in xsl:if nodes:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/rootNode">
        <xsl:if test="node1/text()">
        has text
        </xsl:if>
        <xsl:if test="node1/*">
        has elements
        </xsl:if>
        <xsl:if test="node1[not(node())]">
        is empty
        </xsl:if>
        <xsl:if test="not(node1)">
        no node1
        </xsl:if>
    </xsl:template>
</xsl:stylesheet> 

Solution 2

Will it test for the existence of --> /rootNode/node1 only or check the contents of node1 as well?

It is an existence test.

How does we check the contents of node1 in this expression that it should not be null.

It can't be null if the element is present. It can however be empty. In the case of an element, that would mean it has no children.

Share:
23,141
CuriousMind
Author by

CuriousMind

Updated on October 19, 2020

Comments

  • CuriousMind
    CuriousMind over 3 years

    I am trying to implement an xsl in which a node from an xml be selected only if that element exists and have some value:

    I did some research and this expression i found can be used in the test condition:

    <xsl:if test="/rootNode/node1" >
    
     // whatever one wants to do   
    
    </xsl:if>
    

    Will it test for the existence of --> /rootNode/node1 only or check the contents of node1 as well? How does we check the contents of node1 in this expression that it should not be null.

  • CuriousMind
    CuriousMind over 8 years
    Thanks so much, however how do we specify it in <xsl:if test=" " > </xsl:if>; i don't want to create a <template> rule.
  • CuriousMind
    CuriousMind over 8 years
    May be like this: <xsl:if test="/rootNode/node1/text()" > // whatever one wants to do </xsl:if>