xsl-list
[Top] [All Lists]

Re: Re: Incrementing a Global variable

2003-08-28 07:21:46
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:

This is not a difficult problem and it doesn't deserve all this long thread.

Here's a simple two-pass solution:


<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform";
 xmlns:ext="http://exslt.org/common";

 <xsl:output method="html" indent="yes"/>
 
 <xsl:key name="kStudent" match="student" use="@nl"/>
 
  <xsl:template match="/">
   <html>
    <table>
    <xsl:variable name="vrtfGrouped">
     <xsl:for-each 
      select="/*/student[generate-id()
                     =
                      generate-id(key('kStudent',
                                      @nl
                                      )[1]
                                  )
                      ]">
       <xsl:copy-of select="key('kStudent', @nl)"/>
     
       <xsl:if test="not(position() = last())">
        <blank/>
       </xsl:if>
    
     </xsl:for-each>
    </xsl:variable>
   
    <xsl:variable name="vGrouped" 
        select="ext:node-set($vrtfGrouped)/*"/>
   
    <xsl:for-each select="$vGrouped">
     <tr>
       <td>
         <xsl:value-of select="position()"/>
       </td>
       <td>
         <xsl:value-of select="concat(@name, ' ')"/>
       </td>
     </tr>
    </xsl:for-each>
   </table>
   </html>
  </xsl:template>
</xsl:stylesheet>


When this transformation is applied e.g. on the following source.xml:

<t>
 <student name="x" nl="English"/>
 <student name="y" nl="German"/>
 <student name="z" nl="English"/>
 <student name="t" nl="French"/>
 <student name="u" nl="English"/>
</t>

the wanted result is produced:


<html>
  <table>
    <tr>
      <td>1</td>
      <td>x </td>
    </tr>
    <tr>
      <td>2</td>
      <td>z </td>
    </tr>
    <tr>
      <td>3</td>
      <td>u </td>
    </tr>
    <tr>
      <td>4</td>
      <td> </td>
    </tr>
    <tr>
      <td>5</td>
      <td>y </td>
    </tr>
    <tr>
      <td>6</td>
      <td> </td>
    </tr>
    <tr>
      <td>7</td>
      <td>t </td>
    </tr>
  </table>
</html>


So what is the problem?


=====
Cheers,

Dimitre Novatchev.
http://fxsl.sourceforge.net/ -- the home of FXSL

__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free, easy-to-use web site design software
http://sitebuilder.yahoo.com

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



<Prev in Thread] Current Thread [Next in Thread>