ASPN ActiveState Programmer Network  
ActiveState, a division of Sophos
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups
Submit Recipe
My Recipes

All Recipes
All Cookbooks


View by Category

Title: Count previous nodes
Submitter: Paul Prescod (other recipes)
Last Updated: 2001/08/23
Version no: 1.0
Category: XPath Tricks

 

Not Rated yet


Approved

Description:

It is sometimes useful to count nodes that precede the current one. One way is to use the built-in xsl:count instruction but if you use the count() function (as opposed to instruction) with the preceding axis, you can easily use the result of the count in a larger expression.

Source: Text Source

<xsl:template match="PARA">
  My count divided by two:
  <xsl:value-of select="(count(preceding::PARA)+1)/2"/>
</xsl:template>

The license for this recipe is available here.

Discussion:

This recipe counts the PARA's that precede this one. Then it adds one and divides by two. Elements that are ancestors (including the direct parent) of the current node are excluded from the count.

Namespace nodes and attribute nodes are also excluded from the count though that is rarely an issue.



Add comment

Number of comments: 2

Correction and comment, Evan Lenz, 2001/09/19
The example shown contains a syntax error. Instead of "/", the XPath division operator is "div". So, it should say "(count(preceding::PARA)+1) div 2".

When you say xsl:count, I assume you must mean xsl:number? (There's no xsl:count instruction in XSLT 1.0)

As it happens in this particular example, a more common idiom would be to use the XPath position() function to get the position of the current node in the current node list. For example, if this template is being matched because <xsl:apply-templates select="PARA"/> had been called, then the current node list will consist of only PARA elements, and the position() function will return the integer position of each one in the list, as it is matched. This usage is not equivalent, of course, to what's presented here, but it will work the same in cases where the current node list consists (only) of all PARA elements in the source tree up to a given point.
Add comment

Not specified Not specified, 2007/04/17
Yes there is: XPath function: number count (node-set) Standard excerpt: The count function returns the number of nodes in the argument node-set.
Add comment



Highest rated recipes:

1. Search and Replace

2. Generating a newline

3. Internationalization ...

4. Restricting processing ...

5. Result Pagination with ...

6. Fetching information ...

7. Getting text children of ...

8. Creating empty elements




Privacy Policy | Email Opt-out | Feedback | Syndication
© 2006 ActiveState Software Inc. All rights reserved.