簡體   English   中英

獲取XSLT for-each循環中的元素總數(迭代)

[英]Get the total number of elements (iterations) in an XSLT for-each loop

我通常使用jquery模板來做這種事情,但是我繼承了一個我需要更新的XSLT文件,但我找不到一種方法來獲取特定模板調用的元素總數(迭代)。

使用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>

如果你循環一些$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)以獲取迭代次數。

Wayne的答案是有效的,並且在某些情況下可能是必要的,當必須滿足其他要求時。 但是,如果你有一個簡單的情況,你可以使用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,輸出與Wayne的結果相同。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM