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.
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With