2011-12-28 54 views
3

我通常使用jquery模板来处理这类事情,但我继承了需要更新的XSLT文件,但是我找不到获取特定模板调用的元素总数(迭代)。在XSLT for each each循环中获取元素的总数(迭代)

有了jQuery模板,我会做这样的事情,它会给我循环的资产总数。

<span id="${spnID}"> 
    ${GroupName} (${Assets.length}) 
</span> 

如果循环中有五个元素,这将返回“Product x(5)”。

看起来很简单,但我似乎无法找到一种方法来用XSLT做同样的事情。像这样的东西,我想:

<span id="{$SpnId}"> 
    <xsl:value-of select="$GroupName"/> (<xsl:value-of select="$total-number-of-elements"/>) 
</span> 
+0

什么问题?你能提供输入XML吗? – 2011-12-28 18:07:41

+0

也许XPath [计数函数](http://msdn.microsoft.com/en-us/library/ms256103.aspx)是你在找什么? – Scott 2011-12-28 18:39:58

回答

8

如果你遍历一些$set然后输出count($set)去迭代项目的总数。例如,试试这个样式表:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output method="text" /> 
    <xsl:template match="/"> 
     <xsl:variable name="set" select="/table/row" /> 
     <xsl:variable name="count" select="count($set)" /> 
     <xsl:for-each select="$set"> 
      <xsl:value-of select="concat(position(), ' of ', $count, '&#xa;')" /> 
     </xsl:for-each> 
    </xsl:template> 
</xsl:stylesheet> 

在此输入:

<table> 
    <row id="1" /> 
    <row id="2" /> 
    <row id="3" /> 
    <row id="4" /> 
    <row id="5" /> 
    <row id="6" /> 
</table> 

输出:

1 of 6 
2 of 6 
3 of 6 
4 of 6 
5 of 6 
6 of 6 

注意,我们遍历通过/table/row选择的节点和输出count(/table/row)到得到迭代次数。

+0

这正是我所期待的。谢谢! – Aaron 2012-01-10 23:08:50

1

韦恩的答案有效,在某些情况下可能是必要的,当时还有其他要求必须得到满足。但是,如果你有一个简单的情况,你可以通过使用Last()函数更高效地完成它。只要处理了for-each,Last()就包含该集合的上限或计数。

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output method="text" /> 
    <xsl:template match="/"> 
    <xsl:for-each select="/table/row"> 
     <xsl:value-of select="concat(position(), ' of ', last(), '&#xa;')" /> 
    </xsl:for-each> 
</xsl:template> 

对同一XML运行,输出是相同的韦恩的结果。

1 of 6 
2 of 6 
3 of 6 
4 of 6 
5 of 6 
6 of 6