2014-10-02 49 views
0

我想從xml文檔使用xslt構建一個html表格。該XML的代碼如下所示:計算一個類型的所有以前的元素達到根

<root> 
    <group> 
     <name>A</name> 
     <item>1</item> 
     <item>2</item> 
     <item>3</item> 
    </group> 
    <group> 
     <name>B</name> 
     <item>4</item> 
     <item>5</item> 
    </group> 
</root> 

表應該是這樣的:

<table> 
    <tr> 
     <th>Group</th> 
     <th>Item</th> 
    </tr> 
    <tr class="row_0"> 
     <td>A</td> 
     <td>1</td> 
    </tr> 
    <tr class="row_1"> 
     <td>.</td> 
     <td>2</td> 
    </tr> 
    <tr class="row_0"> 
     <td>.</td> 
     <td>3</td> 
    </tr> 
    <tr class="row_1"> 
     <td>B</td> 
     <td>4</td> 
    </tr> 
    <tr class="row_0"> 
     <td>.</td> 
     <td>5</td> 
    </tr> 
</table> 

的問題是類屬性的交替(這是需要的造型,因爲我不可以訪問現代CSS僞類)該類應始終在row_0row_1之間交替。因爲表的佈局,它可以被表述爲這樣的事:

<xsl:attribute name="class">row_<xsl:value-of select="count(all previous item elements) mod 2" /></xsl:attribute> 

我怎樣才能表達all previous item elements作爲一個真正的選擇?它還必須計算以前組中的所有item元素。然而,它應該只數到root(根在這個例子是不是我的實際文件的root

編輯: 我現在的XSLT看起來像這樣

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output method="html" /> 
    <xsl:template match="root"> 
     <table> 
      <tr> 
       <th>Group</th> 
       <th>Item</th> 
      </tr> 

      <xsl:for-each select="group"> 
       <tr> 
        <xsl:attribute name="class">row_<xsl:value-of select="position() mod 2" /></xsl:attribute> 
        <td><xsl:value-of select="name" /></td> 
        <xsl:for-each select="item"> 
         <xsl:if test="position() = 1"> 
          <td><xsl:value-of select="text()" /></td> 
         </xsl:if> 
        </xsl:for-each> 
       </tr> 
       <xsl:for-each select="item"> 
        <xsl:if test="position() > 1"> 
         <tr> 
          <xsl:attribute name="class">row_<xsl:value-of select="position() mod 2" /></xsl:attribute> 
          <td>.</td> 
          <td><xsl:value-of select="text()" /></td> 
         </tr> 
        </xsl:if> 
       </xsl:for-each> 
      </xsl:for-each> 
     </table> 
    </xsl:template> 
</xsl:stylesheet> 

兩個屬性,它說position() mod 2將需要更換。

+0

你已經產生的表的XSLT樣式表?如果是,請將其添加到您的問題中,以節省我們的一些工作。 – 2014-10-02 12:56:40

回答

1

讓我提出一個簡單的方法:

<xsl:template match="/root"> 
    <table> 
     <tr> 
      <th>Group</th> 
      <th>Item</th> 
     </tr> 
     <xsl:for-each select="group/item"> 
      <tr class="row_{(position() - 1) mod 2}"> 
       <td> 
        <xsl:choose> 
         <xsl:when test="not(preceding-sibling::item)"> 
          <xsl:value-of select="../name" /> 
         </xsl:when> 
         <xsl:otherwise> 
          <xsl:text>&#160;</xsl:text> 
         </xsl:otherwise> 
        </xsl:choose> 
       </td> 
       <td><xsl:value-of select="."/></td> 
      </tr>    
     </xsl:for-each> 
    </table> 
</xsl:template> 
+0

你更簡單的方法是歡迎!我對xslt瞭解不多,但必須在工作中使用它,知道其他人也知道它。我只是應用了我從一些遺留代碼中挑選的內容。 – edave 2014-10-02 13:29:20

相關問題