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

I am using the XPath equivalent for a loop -

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

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

Thanks,

Ash.

+4
source share
3 answers

No additional namespaces are required below. The solution contains a template called iterate , which is called internally and which updates $length and $i respectively:

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> 

Exit

 <?xml version="1.0" encoding="UTF-8"?> <root> <pos>1</pos> <pos>2</pos> <pos>3</pos> <pos>4</pos> <pos>5</pos> </root> 
+4
source

First of all, we note that

 for $i in 1 to $length return $i 

is just a long way to write

 1 to $length 

Inside each of them, you can access the current integer value as ".". or as position() .

+7
source

Inside

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

the context element is an integer value, so you just need to access . or current() .

+6
source

Source: https://habr.com/ru/post/1495690/


All Articles