Xml 将xsl:template的执行次数限制为指定的次数

Xml 将xsl:template的执行次数限制为指定的次数,xml,xslt,loops,Xml,Xslt,Loops,以下是我的XSLT: <!-- Looping through both Items and Categories of Items --> <xsl:for-each select="statement"> <!-- Define whether current node is a single item or a category of items --> <xsl:choose> <!-- Categ

以下是我的XSLT:

<!-- Looping through both Items and Categories of Items -->
<xsl:for-each select="statement">

    <!-- Define whether current node is a single item or a category of items -->
    <xsl:choose>

        <!-- Category of items -->
        <xsl:when test="statement">

            <!-- Render all items in this category -->
            <xsl:for-each select="statement">
                <xsl:call-template name="renderItem" select="current()" />
            </xsl:for-each>

        </xsl:when>

        <!-- Single item -->
        <xsl:otherwise>
            <xsl:call-template name="renderItem" select="." />
        </xsl:otherwise>

    </xsl:choose>

</xsl:for-each>

我希望能够输出特定数量的项目,但不是全部。
如何使“renderItem”的执行次数不超过(比如)4次?

问题的解决方案依赖于使用递归,手动控制模板的执行次数(或计算项目的渲染次数)

这更多的是一个如何实现它的想法,而不是解决您的问题(我不知道您的XML文件是什么样子的),但我已经尝试调整您发布的代码(可能是错误的,没有XML我不确定)


然后可以使用(或类似的方法)调用模板


您的代码看起来很奇怪:所有这些xsl:choose、xsl:for each和xsl:call模板看起来像是应用模板和模板规则的自制实现。此外,xsl:call模板不接受select属性——这是一个语法错误,您的XSLT处理器应该将其标记为select属性,而不是简单地忽略它

忽略这一点,我认为解决问题的最简单方法是通过检查项目在树中的位置来测试是否要处理项目。差不多

<xsl:template match="statement">
  <xsl:variable name="pos">
    <xsl:number level="any" from="..."/>
  </xsl:variable>
  <xsl:if test="$pos &lt; 5">...
</xsl:template>

...

Michael,这是一个伪代码,不是真的,所以,你是对的,它很可能不起作用。感谢您发布您的解决方案,我会尝试一下。Pablo,感谢您发布此解决方案。我试试看。
<xsl:call-template name="renderItems">
    <xsl:with-param name="items"
                    select="statement" />
</xsl:call-template>
<xsl:template match="statement">
  <xsl:variable name="pos">
    <xsl:number level="any" from="..."/>
  </xsl:variable>
  <xsl:if test="$pos &lt; 5">...
</xsl:template>