Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

xml

xslt

xslt-1.0

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.

like image 969
CuriousMind Avatar asked Sep 16 '25 02:09

CuriousMind


2 Answers

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> 
like image 187
Thomas Weller Avatar answered Sep 17 '25 19:09

Thomas Weller


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.

like image 35
user207421 Avatar answered Sep 17 '25 18:09

user207421