Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xslt test to see if a node is one of the first X children of its parent

Tags:

xslt

xpath

I am editing an XSLT template and my skills are a little rusty.

I would like to write a condition to see if the current node is in the first three child nodes of its parent.

<parent>
 <child>
 <child>
 <child>
 <child>
</parent>

So the first three child elements above would return true, but the fourth would return false, to complicate matters the child elements will not all be the same and will have descendants of their own. I am sure there is some simple xpath that will do it.

like image 973
Jeremy French Avatar asked Aug 03 '09 14:08

Jeremy French


1 Answers

It depends on the situation. If you are in the middle of

<xsl:apply-templates select="/parent/child" />

Then checking with

<xsl:if test="position() &lt; 4">

will do. If you are in some other context, one that does not affect all <child> elements, then position() will refer to the position within that context.

If you want a context-free check, you can use:

<xsl:if test="count(preceding-sibling::child) &lt; 3">
<!-- or -->
<xsl:if test="count(preceding-sibling::*) &lt; 3">

To select only the first three <child> elements, this would be it:

/parent/child[position() &lt; 4]
like image 199
Tomalak Avatar answered Nov 26 '22 06:11

Tomalak