Implementation
We’ll define four global parameters for our stylesheet:
<xsl:param name="i" select="1"/> <xsl:param name="increment" select="1"/> <xsl:param name="operator" select="'<='"/> <xsl:param name="testValue" select="10"/>
The default values defined here correspond to the C++ or Java
statement for (i = 1; i <= 10;
i++). We also have a match="/" template that invokes our for loop processor:
<xsl:template match="/">
<xsl:call-template name="for-loop">
<xsl:with-param name="i" select="$i"/>
<xsl:with-param name="increment" select="$increment"/>
<xsl:with-param name="operator" select="$operator"/>
<xsl:with-param name="testValue" select="$testValue"/>
</xsl:call-template>
</xsl:template>In the for-loop template, our
first task is to determine whether the condition is true. We do this
by calculating a boolean value with several <xsl:when> elements, each of which
looks like the one below:
<xsl:variable name="testPassed">
<xsl:choose>
<xsl:when test="$operator = '!='">
<xsl:if test="$i != $testValue">
<xsl:text>true</xsl:text>
</xsl:if>
</xsl:when>
...
</xsl:variable>If the variable $testPassed
is true, the for-loop template calls itself again. Before
the <xsl:call-template>
instruction, we can put whatever logic we want. For our sample, we
simply write the current value of $i to the output.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access