2008-09-18 107 views
80

如何在xsl:for-each循環內部獲得一個計數器,以反映當前處理元素的數量。
例如我的源XML是xsl:for-each循環內部的計數器

<books> 
    <book> 
     <title>The Unbearable Lightness of Being </title> 
    </book> 
    <book> 
     <title>Narcissus and Goldmund</title> 
    </book> 
    <book> 
     <title>Choke</title> 
    </book> 
</books> 

我想要得到的是:

<newBooks> 
    <newBook> 
     <countNo>1</countNo> 
     <title>The Unbearable Lightness of Being </title> 
    </newBook> 
    <newBook> 
     <countNo>2</countNo> 
     <title>Narcissus and Goldmund</title> 
    </newBook> 
    <newBook> 
     <countNo>3</countNo> 
     <title>Choke</title> 
    </newBook> 
</newBooks> 

的XSLT修改:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> 
    <xsl:template match="/"> 
     <newBooks> 
      <xsl:for-each select="books/book"> 
       <newBook> 
        <countNo>???</countNo> 
        <title> 
         <xsl:value-of select="title"/> 
        </title> 
       </newBook> 
      </xsl:for-each> 
     </newBooks> 
    </xsl:template> 
</xsl:stylesheet> 

所以,問題是要放什麼地方???。有沒有任何標準關鍵字,或者我只需要聲明一個變量並在循環內增加它?

由於問題相當長的我也許應該期待一個線或一個字的回答:)

回答

130

position()。例如: -

<countNo><xsl:value-of select="position()" /></countNo> 
+1

需要關閉報價「添加到屬性值 – 2008-10-22 08:27:07

+6

這是所有罰款和花花公子,直到你必須添加過濾器一樣的xsl:如果您的XSL內:對,每個然後位置()是沒有用的,並你需要適當的計數器 – 2012-03-19 16:00:53

+2

@Mike Stavrov這不是問題的一部分不能涵蓋所有情況 – redsquare 2012-03-19 21:10:54

5
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> 
    <xsl:template match="/"> 
     <newBooks> 
       <xsl:for-each select="books/book"> 
         <newBook> 
           <countNo><xsl:value-of select="position()"/></countNo> 
           <title> 
             <xsl:value-of select="title"/> 
           </title> 
         </newBook> 
       </xsl:for-each> 
     </newBooks> 
    </xsl:template> 
</xsl:stylesheet> 
13

嘗試在???的位置插入<xsl:number format="1. "/><xsl:value-of select="."/><xsl:text>

請注意「1.」 - 這是數字格式。更多信息:here

5

嘗試:

<xsl:value-of select="count(preceding-sibling::*) + 1" /> 

編輯 - 有腦凍在那裏,位置()更簡單!

5

您還可以在Postion()上運行條件語句,這在許多情況下可能非常有用。

例如。

<xsl:if test="(position()) = 1"> 
    //Show header only once 
    </xsl:if>