4

I am using the XPath for loop equivalent -

<xsl:for-each select="for $i in 1 to $length return $i">...

And I really need a count variable, how would I achieve this?

Thanks,

Ash.

Ash
  • 8,583
  • 10
  • 39
  • 52

3 Answers3

10

First note that

for $i in 1 to $length return $i

is just a long-winded way of writing

1 to $length

Within the for-each, you can access the current integer value as "." or as position().

Michael Kay
  • 156,231
  • 11
  • 92
  • 164
6

Inside of the

<xsl:for-each select="for $i in 1 to $length return $i">...</xsl:for-each>

the context item is the integer value so you simply need to access . or current().

Martin Honnen
  • 160,499
  • 6
  • 90
  • 110
5

The following requires no additional namespaces. The solution contains a template called iterate that is called from within itself and which updates $length and $i accordingly:

XSLT

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
        <root>
            <xsl:call-template name="iterate"/>
        </root>
    </xsl:template>
    <xsl:template name="iterate">
        <xsl:param name="length" select="5"/>
        <xsl:param name="i" select="1"/>
        <pos><xsl:value-of select="$i"/></pos>
        <xsl:if test="$length > 1">
            <xsl:call-template name="iterate">
                <xsl:with-param name="length" select="$length - 1"/>
                <xsl:with-param name="i" select="$i + 1"/>
            </xsl:call-template>
        </xsl:if>
    </xsl:template>
</xsl:stylesheet>

Output

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <pos>1</pos>
    <pos>2</pos>
    <pos>3</pos>
    <pos>4</pos>
    <pos>5</pos>
</root>
Jens
  • 8,423
  • 9
  • 58
  • 78
Matthew Warman
  • 3,234
  • 2
  • 23
  • 35
  • Not sure why this incredibly verbose solution has been accepted when other responses suggest a much more succinct solution. – Michael Kay Aug 12 '13 at 11:13
  • I have to agree with @MichaelKay I originally misread the question and was under the impression `for $i in 1 to $length return $i` didn't work and was just a concept, the answer provided by Michael (and Martin) works as required. – Matthew Warman Aug 12 '13 at 13:04