iterate in XSLT. iteration, recursion

Iteration

1. Iteration in XSLT
2. Iterating over a sequence

1.

Iteration in XSLT

David Carlisle


Given

<x>
   <count>5</count>
   <Hello>Hello, World!</Hello>
</x>

you could do something like this (untested)

<xsl:template match="x">
 <xsl:apply-template select="Hello"/>
</xsl:tenplate>

<xsl:template match="Hello">
 <xsl:param name="x" select="/x/count"/>
 <xsl:copy-of select="."/>
 <xsl:if test="$x > 1">
   <xsl:apply-template select=".">
    <xsl:with-param name="x" select="$x - 1"/>
   </xsl:apply-template>
 </xsl:if>
</xsl:template>


2.

Iterating over a sequence

Michael Kay


> I would like to create a loop which iterates through each letter of 
> the (English) alphabet.

> This approach prints each letter of the alphabet:

> <xsl:variable name="letters" 
> select="'a','b','c','d','e','f','g','h','i','j','k','l','m','n
> ','o','p','q','r','s','t','u','v','w','x','y','z'"/>
> <xsl:for-each select="1 to 26">
>      <xsl:variable name="idx" select="."/>
>      <xsl:value-of select="$letters[$idx]"/> </xsl:for-each>

> On the other hand, this approach prints the entire alphabet 26 times:

> <xsl:variable name="letters" 
> select="'a','b','c','d','e','f','g','h','i','j','k','l','m','n
> ','o','p','q','r','s','t','u','v','w','x','y','z'"/>
> <xsl:for-each select="1 to 26">
>      <xsl:value-of select="$letters[.]"/> </xsl:for-each>

> I am baffled.  Both versions are indexing the $letters sequence 
> variable with the (integer) loop iteration value, right? 

A predicate changes the context. Inside a predicate [], "." refers to the item in the sequence being tested.