2010-04-20 32 views
1

我需要在表格中顯示RSS源(從網上商店系統獲得它的衣服)。 RSS中的圖像在寬度和高度上有所不同,我想製作一個表格來顯示它們。首先,我很高興只顯示3列中的所有項目,但是在更遠的路上,我需要能夠通過參數指定表格中的列數。我遇到一個問題顯示tr標籤,並使其正確的,這是到目前爲止我的代碼:使用不同數量的列創建表格的XSLT

<xsl:template match="item"> 
    <xsl:choose>  
     <xsl:when test="position() mod 3 = 0 or position()=1"> 
     <tr> 
      <td> 
      <xsl:value-of select="title"/> 
      </td> 
     </tr> 
     </xsl:when> 
     <xsl:otherwise> 
     <td> 
      <xsl:value-of select="title"/> 
     </td> 
     </xsl:otherwise> 
    </xsl:choose>  
    </xsl:template> 

在RSS所有「項目」標籤上的XML同一水平線上,因此到目前爲止,我需要只有標題顯示。這個問題似乎是我需要指定開始標記以及tr元素的結束標記,並且無法獲取所有3個元素,任何人都知道如何做到這一點?

回答

2

當你退後一點時很容易。將問題分解成更小的部分。

<xsl:param name="numColumns" select="3" /> 

<xsl:template match="channel"> 
    <table> 
    <!-- all items that start a column have position() mod x = 1 --> 
    <xsl:apply-templates 
     select="item[position() mod $numColumns = 1]" 
     mode="tr" 
    /> 
    </table> 
</xsl:template> 

<xsl:template match="item" mode="tr"> 
    <tr> 
    <!-- all items make a column: this one (.) and the following x - 1 --> 
    <xsl:apply-templates 
     select=".|following-sibling::item[position() &lt; $numColumns]" 
     mode="td" 
    /> 
    </tr> 
</xsl:template> 

<xsl:template match="item" mode="td"> 
    <td> 
    <!-- calculate optional colspan for the last td --> 
    <xsl:if test="position() = last() and position() &lt; $numColumns"> 
     <xsl:attribute name="colspan"> 
     <xsl:value-of select="$numColumns - position() + 1" /> 
     </xsl:attribute> 
    </xsl:if> 
    <xsl:value-of select="title"/> 
    </td> 
</xsl:template> 
+0

非常好。我花了一半時間去了解如何去做。非常感謝你! – Claudix 2012-09-19 15:56:25

+0

@Claudix你非常歡迎。很高興看到舊的東西仍然有助於人們。 – Tomalak 2012-09-19 16:02:35

+0

沒有在互聯網上死去的地方:-) – Claudix 2012-09-19 16:38:05