Xslt to find out if a node is one of the first X-children of its parent

I am editing an XSLT template and my skills are a bit 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 children above will return true, but the fourth will return false to complicate the issue that the children will not be the same and will have their children. I am sure there is a simple xpath that will do this.

+7
xpath xslt
source share
2 answers

It depends on situation. If you are in the middle

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

Then using

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

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

If you need a context 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, it will be:

 /parent/child[position() &lt; 4] 
+17
source share

Call the position() function to determine where the node exists in the document.

0
source share

All Articles