2011-12-28 48 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