O'Reilly logo

XSLT, 2nd Edition by Doug Tidwell

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Name

count()

Counts the number of nodes in a given [1.0] node-set or [2.0] sequence.

Syntax

[1.0] number count(node-set)
[2.0] xs:integer count(item()*)

Inputs

A node-set or sequence.

Output

The number of items in the node-set or sequence. [2.0] If the argument is the empty sequence, count() returns 0.

Defined in

[1.0] XPath section 4.1, “Node Set Functions.”

[2.0] XQuery 1.0 and XPath 2.0 Functions and Operators section 15.4, “Aggregate Functions.”

Examples

Here’s the XML document we’ll use to illustrate the count() function:

<?xml version="1.0" encoding="utf-8"?>
<!-- chocolate.xml -->
<report month="8" year="2006">
  <title>Chocolate bar sales</title>
  <brand>
    <name>Lindt</name>
    <units>27408</units>
  </brand>
  <brand>
    <name>Callebaut</name>
    <units>8203</units>
  </brand>
  <brand>
    <name>Valrhona</name>
    <units>22101</units>
  </brand>
  <brand>
    <name>Perugina</name>
    <units>14336</units>
  </brand>
  <brand>
    <name>Ghirardelli</name>
    <units>19268</units>
  </brand>
</report>

And our stylesheet that illustrates the count() function:

<?xml version="1.0"?>
<!-- count.xsl -->
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:output method="text"/>

  <xsl:template match="/">
    <xsl:text>&#xA;Tests of the count() function:&#xA;&#xA;</xsl:text>

    <xsl:text>  Our store sells </xsl:text>
    <xsl:value-of select="count(/report/brand)"/>
    <xsl:text> different brands of chocolate.</xsl:text>
    <xsl:text>&#xA;&#xA;  For the last month, </xsl:text>
 <xsl:value-of select="count(/report/brand[units > 20000])"/> ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required