Node-Set Functions

The node-set functions operate on or return information about node-sets; that is, collections of XPath nodes. You’ve already encountered the position( ) function. Two related functions are last( ) and count(). The last( ) function returns the number of nodes in the context node list, which also happens to be the same as the position of the last node in the list. The count( ) function is similar except that it returns the number of nodes in its node-set argument rather than in the context node list. For example, count(//name) returns the number of name elements in the document. Example 9-5 uses the position() and count( ) functions to list the people in the document in the form “Person 1 of 10, Person 2 of 10, Person 3 of 10...”. In the second template, the position( ) function determines which person element is currently being processed, and the count( ) function determines how many total person elements there are in the document.

Example 9-5. An XSLT stylesheet that uses the position( ) and count( ) functions
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
     
  <xsl:template match="people">
    <xsl:apply-templates select="person"/>
  </xsl:template>
     
  <xsl:template match="person">
    Person <xsl:value-of select="position( )"/>
    of <xsl:value-of select="count(//person)"/>:
    <xsl:value-of select="name"/>
  </xsl:template>
     
</xsl:stylesheet>

The id( ) function takes as an argument a string containing one or more IDs separated ...

Get XML in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.