December 29, 2001 - Looping in XSLT | WebReference

December 29, 2001 - Looping in XSLT

Yehuda Shiran December 29, 2001
Looping in XSLT
Tips: December 2001

Yehuda Shiran, Ph.D.
Doc JavaScript

The amazing capability of XSLT is its ability to loop through data. You can direct XSLT to search for a specific tag, and then loop through all this tag's children. You start an XSLT loop with the <xsl:for-each> tag. You specify the data element to loop through by the select attribute of this tag. Suppose the data is as shown below, and you want to loop through the four different weeks of the first-month record. You will do it by writing:

<xsl:for-each select="//data/month[1]/week">
Besides looping, you probably want to do some useful stuff while at it. Suppose you want to prepare headers for four columns. The first column will be named W1 (for Week 1), the second column is W2, the third is W3, and the last one is W4. You can print the character W and concatenate the number of the week to it. You can pick the serial number of the week from the number attribute, through the <xsl:value-of /> tag:

<xsl:value-of select="@number"/>
Combining the opening-loop tag, the core of the loop, and the closing-loop tag looks like this:

<xsl:for-each select="//data/month[1]/week">
<TH>W<xsl:value-of select="@number"/></TH>
</xsl:for-each>
Let's add two more columns. The first column will be the string "Month\Week", and the last one will be the string "Total". As you have probably already noticed, we also format the columns in an HTML TABLE:

<TABLE>
<TR>
<TH>Month\Week</TH>
<xsl:for-each select="//data/month[1]/week">
<TH>W<xsl:value-of select="@number"/></TH>
</xsl:for-each>
<TH>Total</TH>
</TR>
</TABLE> 
Here is how these column headers look like:

Here is the XML file:

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="011229.xsl"?>
  <sales>
    <summary>
      <heading>MyDvd Rental Store</heading>
      <subhead>Periodical Sales Report</subhead>
      <description>Sales Report for January, February, and March of 2001</description>
    </summary>
    <data>
      <month>
        <name>January 2001</name>
        <week number="1" dvds_rented="12000" />
        <week number="2" dvds_rented="15000" />
        <week number="3" dvds_rented="18000" />
        <week number="4" dvds_rented="11000" />		  
      </month>
      <month>
        <name>February 2001</name>
        <week number="1" dvds_rented="11000" />
        <week number="2" dvds_rented="12390" />
        <week number="3" dvds_rented="10050" />
        <week number="4" dvds_rented="11200" />		  
      </month>
      <month>
	    <name>March 50</name>
        <week number="1" dvds_rented="11000" />
        <week number="2" dvds_rented="12390" />
        <week number="3" dvds_rented="10050" />
        <week number="4" dvds_rented="11200" />		  
      </month>
    </data>
  </sales>