Ash
Ash

Reputation: 9081

Creating an incremental count variable in XSLT / XPath when using Xpath for..in..return?

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.

Upvotes: 4

Views: 31869

Answers (3)

Matthew Warman
Matthew Warman

Reputation: 3442

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>

Upvotes: 5

Michael Kay
Michael Kay

Reputation: 163322

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().

Upvotes: 10

Martin Honnen
Martin Honnen

Reputation: 167561

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().

Upvotes: 6

Related Questions