Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xslt/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Variables 为..in..return使用XPath时在XSLT/XPath中创建增量计数变量?_Variables_Xslt_Xpath_For Loop_Count - Fatal编程技术网

Variables 为..in..return使用XPath时在XSLT/XPath中创建增量计数变量?

Variables 为..in..return使用XPath时在XSLT/XPath中创建增量计数变量?,variables,xslt,xpath,for-loop,count,Variables,Xslt,Xpath,For Loop,Count,我正在使用XPath for循环等价物- <xsl:for-each select="for $i in 1 to $length return $i">... 。。。 我真的需要一个计数变量,我该如何实现呢 谢谢 Ash.以下内容不需要额外的名称空间。解决方案包含一个名为iterate的模板,该模板从自身内部调用,并相应地更新$length和$i: XSLT <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.or

我正在使用XPath for循环等价物-

<xsl:for-each select="for $i in 1 to $length return $i">...
。。。
我真的需要一个计数变量,我该如何实现呢

谢谢


Ash.

以下内容不需要额外的名称空间。解决方案包含一个名为
iterate
的模板,该模板从自身内部调用,并相应地更新
$length
$i

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>

输出

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

1.
2.
3.
4.
5.

<xsl:for-each select="for $i in 1 to $length return $i">...</xsl:for-each>
。。。
上下文项是整数值,因此您只需访问
current()

首先要注意

for $i in 1 to $length return $i
这只是一种冗长的写作方式

1 to $length

在for each中,您可以将当前整数值访问为“.”或
position()

我不知道为什么当其他回答建议更简洁的解决方案时,这个令人难以置信的冗长的解决方案被接受。我不得不同意@MichaelKay的观点,我最初误读了这个问题,并认为
在1到$length中的$I返回$I
不起作用,只是一个概念,这是Michael提供的答案(和马丁)按要求工作。