xsl-list
[Top] [All Lists]

Re: Counting elements with count() and position()

2003-07-10 06:40:05
Thanks Jeni,

That reply was much more than I had hoped for.

One problem - 4 solutions.

I do get a buzz working at home through your 'StarTrek' counting examples
in Begining XSLT then posting a question and getting a reply 10 mins.
later from the author herself.

I look forward to completing this book and moving onto the one beside it
'XSLT and XPATH On The Edge'.

Many thanks,
Best regards
Rudi.



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