Re: [xsl] Counting elements with count() and position()

Subject: Re: [xsl] Counting elements with count() and position()
From: Jeni Tennison <jeni@xxxxxxxxxxxxxxxx>
Date: Thu, 10 Jul 2003 14:05:31 +0100
Hi Rudi,

> The position() function is working well for me however I think
> I'm positioning the count() function incorectly.

You're setting the $addresscount variable within one template and then
trying to use it in another template. When a variable is declared
locally (in a template), it's only in scope for the following siblings
of the variable declaration and their descendants; it isn't in-scope
in other templates.

You need to do one of the following:

1. Use the last() function in your address template to give you the
count of the number of nodes "currently being processed". Since all
the nodes are <address> elements, this will give you the count that
you need:

<xsl:template match="address">
  <tr>
    <xsl:choose>
      <xsl:when test="position() = 1">
        <td class="title">
          <xsl:choose>
            <xsl:when test="last() > 1">urls:</xsl:when>
            <xsl:otherwise>url:</xsl:otherwise>
          </xsl:choose>
        </td>
      </xsl:when>
      ...
    </xsl:choose>
    ...
  </tr>
</xsl:template>

2. Make the variable global, so that it's in-scope everywhere. At the
top level of the stylesheet, add:

<xsl:variable name="addresscount"
              select="count(/webapps/website/address)" />

3. Calculate the value for the variable within the address template:

<xsl:template match="address">
  <xsl:variable name="addresscount" select="count(../address)" />
  ...
</xsl:template>

4. Pass the value of $addresscount as a parameter into the address
template. The address template needs to declare the parameter:

<xsl:template match="address">
  <xsl:param name="addresscount" />
  ...
</xsl:template>

and you need to pass it when you apply templates to the <address>
elements:

  <xsl:apply-templates select="address">
    <xsl:with-param name="addresscount" select="$addresscount" />
  </xsl:apply-templates>

Cheers,

Jeni

---
Jeni Tennison
http://www.jenitennison.com/


 XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list


Current Thread