Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XSL - Execute code if a node has a given node as parent

Tags:

xml

xslt

I have the following XML (simplified):

<node1>
    <node2>
        <node3>
        </node3>
    </node2>
</node1>

And I need to determine (using XSL) if node3 has a parent named node1 (not only the inmediate parent, so in the example node3 is a child of node1)

The following code is not working:

<xsl:if test="parent::node1">

</xsl:if>

Thank you

like image 375
Guido Avatar asked Dec 23 '22 06:12

Guido


2 Answers

node3 is not a direct child, it is a descendant. Use the ancestor axis instead, which selects all ancestors (parent, grandparent, etc.) of the current node.

http://www.w3schools.com/xpath/xpath_axes.asp

<xsl:if test="ancestor::node1">

</xsl:if>
like image 151
Mads Hansen Avatar answered Jan 06 '23 00:01

Mads Hansen


try this:

<xsl:if test="count(ancestor::node1)&gt;0">

</xsl:if>

You can omit the count if you like, it is not required. It can be useful when you are in a recursive structure to find the depth the current node is at.

like image 27
Gerco Dries Avatar answered Jan 05 '23 23:01

Gerco Dries