You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在XSLT中利用变量控制for-each循环的迭代次数?

解决XSLT按变量值控制for-each循环次数的问题

你的核心需求是让for-each循环根据Counter变量的值(比如7)迭代对应次数,但当前代码无法实现——原因是<xsl:for-each select="$Counter">中的$Counter是单一数值,而非节点集合或序列,for-each只会执行一次。以下分版本给出解决方案:

XSLT 2.0及以上版本(推荐)

利用XSLT2.0支持的序列生成语法1 to $Counter,直接生成对应次数的序列来控制循环:

<xsl:variable name="Counter" select="Element[1]/@Record_Counter" />
<!-- 提前存储需要输出的属性值,避免循环中上下文变化导致路径错误 -->
<xsl:variable name="ReportingValue" select="Element/@Reporting" />
<xsl:variable name="ValuationValue" select="Element/@Valuation" />

<xsl:for-each select="1 to $Counter">
    <itemGroup ref="ValTechnique">
        <reportItem key="yes">
            <itemValue>
                <xsl:value-of select="$ReportingValue"/>
            </itemValue>
        </reportItem>
        <reportItem>
            <itemValue>
                <xsl:value-of select="$ValuationValue"/>
            </itemValue>
        </reportItem>
    </itemGroup>
</xsl:for-each>

注意:循环内的上下文是序列中的每个数字(1、2……$Counter),所以要提前把@Reporting和@Valuation的值存入变量,或者用绝对路径定位节点。

XSLT 1.0版本

XSLT1.0不支持序列生成,需通过递归模板实现循环:

<xsl:variable name="Counter" select="Element[1]/@Record_Counter" />
<xsl:variable name="ReportingValue" select="Element/@Reporting" />
<xsl:variable name="ValuationValue" select="Element/@Valuation" />

<!-- 启动递归循环,初始计数为1 -->
<xsl:call-template name="repeatLoop">
    <xsl:with-param name="currentCount" select="1" />
    <xsl:with-param name="maxCount" select="$Counter" />
</xsl:call-template>

<!-- 定义递归模板 -->
<xsl:template name="repeatLoop">
    <xsl:param name="currentCount" />
    <xsl:param name="maxCount" />

    <xsl:if test="$currentCount &lt;= $maxCount">
        <itemGroup ref="ValTechnique">
            <reportItem key="yes">
                <itemValue>
                    <xsl:value-of select="$ReportingValue"/>
                </itemValue>
            </reportItem>
            <reportItem>
                <itemValue>
                    <xsl:value-of select="$ValuationValue"/>
                </itemValue>
            </reportItem>
        </itemGroup>
        <!-- 递归调用,计数+1 -->
        <xsl:call-template name="repeatLoop">
            <xsl:with-param name="currentCount" select="$currentCount + 1" />
            <xsl:with-param name="maxCount" select="$maxCount" />
        </xsl:call-template>
    </xsl:if>
</xsl:template>

通过递归模板从1开始计数,直到达到$Counter的值,每次递归输出目标内容。

内容的提问来源于stack exchange,提问作者Vaibhav Shrivastav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 13:19:53