Search code examples
xmlxsltdescendant

XSL: How to test if the current node is a descendent of another node


I'm pretty new to XSLT, but need to use it for a CMS using at the moment. I've already come up with a problem, but I'll try to describe my it without going into too much information about the underlying CMS. If you need more context to help me, I can add it in.

So all I want to do is test if a node of my xml is a descendant of a particular node.

<xsl:if test="$currentNode::IsADescendantOf($someNode)">
Write this out.
</xsl:if>

Any ideas anyone?

Thanks in advance :)


Solution

  • You should use union operation and node-set size comparison:

    <xsl:if test="count($someNode|$currentNode/ancestor::*) = count($currentNode/ancestor::*)">
    Write this out.
    </xsl:if>
    

    If $someNode is an ancestor of $currentNode, $someNode|$currentNode/ancestor::* will return the same node-set as $currentNode/ancestor::* (node-set don't have any doublons).

    If not, the first node-set will have one more node than the second because of the union.