Re: Equivalent of a Global Counter

Subject: Re: Equivalent of a Global Counter
From: Jeni Tennison <mail@xxxxxxxxxxxxxxxx>
Date: Tue, 14 Nov 2000 10:59:43 +0000
Matthew,

> I thought about using parameters for this, but it wouldn't work.
> I need to generate some data in tags, and the data is a number which needs
> to increment for every element encountered. The procedural response is a
> global counter. You can't do this via parameters as the number will
> (effectively) decrement every time you exit an element.

So you want to have something like:

<first>
  <second>
    <third />
  </second>
  <fourth />
</first>

be numbered as:

1. first
2. second
3. third
4. fourth

Is that right?

To get to the declarative solution to the problem, imagine that you
are one of those elements, say 'fourth', you can get the number '4' if
you count how many elements start before you in the document. Looking
at those elements involves looking along the 'preceding' axis
(elements that start and end before you do) and along the 'ancestor'
axis (elements that are still open).

So, you can get the number you're after by counting how many elements
there are on the preceding and ancestor axes, and adding one to it:

  count(preceding::* | ancestor::*) + 1

For example, to number the nodes as above, then:

<xsl:template match="*">
  <xsl:value-of select="count(preceding::* | ancestor::*) + 1" />
  <xsl:text>. </xsl:text>
  <xsl:value-of select="name()" />
  <xsl:apply-templates />
</xsl:template>

I hope that helps,

Jeni

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



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


Current Thread