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

Ev. picture Ev. · Dec 11, 2009 · Viewed 7.9k times · Source

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 :)

Answer

Erlock picture Erlock · Dec 11, 2009

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.