我知道,作为一种函数式语言,XSL 没有传统的 for 循环(但有 for-each)之类的东西。
我正在尝试从可变数量的元素开始创建一个具有固定数量(7)的表。一句话,我有
<items>
<item />
<item />
<item />
</item>
我怎样才能把它变成
<table>
<tr><item /></tr>
<tr><item /></tr>
<tr><item /></tr>
<tr></tr>
<tr></tr>
<tr></tr>
<tr></tr>
</table>
?与count()
很容易计算出我还需要 4 个空的,但是如何做到这一点呢?使用 for 循环我可以轻松解决问题,或者修改 <items>
向其中添加 4 个空元素,但是,作为 xsl 的新手,我什至无法做到这一点。
谢谢
最佳答案
您正在寻找递归解决方案。解决方案包括编写一个模板,当传入的计数小于您需要模板运行的次数时,该模板会调用自身。
IBM 在以下位置发布了一个很好的示例:
http://www.ibm.com/developerworks/xml/library/x-tiploop.html
您的代码可能类似于:
<xsl:template name="itemLoop">
<xsl:param name="count" select="0"/>
<xsl:if test="$count < 7">
<tr><xsl:apply-templates select="/items/item[$count]"/></tr>
<xsl:call-template name="itemLoop">
<xsl:with-param name="count" select="$count + 1"/>
</xsl:call-template>
</xsl:if>
</xsl:template>
关于xslt - XSL : Problem with cicling,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5244919/