Re: [xsl] Incrementing a Global variable

Subject: Re: [xsl] Incrementing a Global variable
From: Bill Keese <billk@xxxxxxxxxxxxxxxxxxxx>
Date: Thu, 28 Aug 2003 19:53:06 +0900
(this is a resend; my original message bounced, I think)

Problem: print a list of students, grouping the students by their language and printing a blank line between each group. Number the blank lines in addition to the lines with students' names.

So calling position() to get the number is insufficient, because position() doesn't count the blank lines.

Mukul was commenting that this problem would be easier to solve if XSLT supported something like variables. For example:

 <xsl:for-each select="Student">
      <xsl:if test="TOption != previous-sibling::Student[last()]/TOption">
           <tr> <td> {counter} </td>  <td/> <td/> </tr>
           counter++;
      </xsl:if>

<tr> <td> {counter} </td> <td> {Name} </td> <td> { Toption } </td> </tr>
counter++;
</xsl:for-each>


This is what Jarno's code essentially does, but Jarno had to use recursion to simulate the loop, which is [arguably] a bit cumbersome. However, you can do something the loop above, if you replace the variable "counter" with a formula, which is
the previous number of students + the previous number of groups


In XSLT version 2 this is simply:

count(preceding-sibling::*) + count(distinct-values(preceding-sibling::*/TOption/text()))

And after the loop finishes, to compute the total number of lines printed, you would do

count(Student) + count(distinct-values(Student/TOption/text()))

-------------
By the way, an alternative to a single loop is to write a nested loop (for-each language / for-each student). This is what Americo's code does, but his code is a bit complicated because he is programming in XSLT V1, where there is no for-each-group operator (http://www.w3.org/TR/xslt20/#d0e15262) . But in XSLT V2 we would say this:


<xsl:for-each-group select="Student" group-by="TOption">
<xsl:variable name="group-no" select="position()"/>
<xsl:for-each select="current-group()">
<tr>
<td> <xsl:value-of select="count(preceding-sibling::*) + $group-no"/> </td>
<td> <xsl:value-of select="Name"/> </td>
<td> <xsl:value-of select="TOption"/> </td>
</tr>
</xsl:for-each>
<tr>
<td> <xsl:value-of select="count(current-group()[last()]/preceding-sibling::*) + $group-no + 1"/> </td>
<td> </td>
<td> </td>
</tr>
</xsl:for-each-group>


Bill


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



Current Thread