This is the mail archive of the
xsl-list@mulberrytech.com
mailing list .
Re: My Difficult counting problem
- From: Jeni Tennison <jeni at jenitennison dot com>
- To: Girard Tim-TGIRARD1 <T dot Girard at motorola dot com>
- Cc: "'XSL-List at lists dot mulberrytech dot com'" <XSL-List at lists dot mulberrytech dot com>
- Date: Thu, 22 Aug 2002 23:07:35 +0100
- Subject: Re: [xsl] My Difficult counting problem
- Organization: Jeni Tennison Consulting Ltd
- References: <715C8C1A871FD511B4920002B328C2769E96B9@IL75EXM04>
- Reply-to: xsl-list at lists dot mulberrytech dot com
Hi Tim,
> I need some help doing the following, I can't seem to figure out how to do
> this in XSL
>
> I need to convert something like this
> <myElement>
> <foo name="foobar1"/>
> <foo name="foobar2"/>
> <foo name="foobar1"/>
> <foo name="foobar3"/>
> <foo name="foobar1"/>
> <foo name="foobar1"/>
> <foo name="foobar3"/>
> </myElement>
>
> and the output after running it through the XSL would be
>
> numberOccurrences[] = {1, 1, 2, 1, 3, 4, 2};
>
> basically for each foo with a duplicate name you put the occurrence
> number of it in the array at the correct position.
>
> You see that foobar1 occurs 4 times,
> the 1st occurrence is at position 0, while 2nd occurrence is at position 2,
> 3rd at position 4, and 5th at position 5. etc.
>
> I don't know how loop through the nodes, and keep track of how many
> occurrences there are up to the given position.
It's easiest to loop through the nodes and when you're on each node
look back and count how many preceding sibling foo elements there are
with the same name, then add one to get the position of this one. Try:
<xsl:template match="myElement">
numberOccurrences[] = {<xsl:apply-templates select="foo" />};
</xsl:template>
<xsl:template match="foo">
<xsl:variable name="name" select="@name" />
<xsl:value-of
select="count(preceding-sibling::foo[@name = $name]) + 1" />
<xsl:if test="position() != last()">, </xsl:if>
</xsl:template>
Cheers,
Jeni
---
Jeni Tennison
http://www.jenitennison.com/
XSL-List info and archive: http://www.mulberrytech.com/xsl/xsl-list