2012-02-13 28 views
2

我遇到了XSLT難題 - 您無法在一個條件語句中打開元素並在另一個條件語句中關閉它。我在Stackoverflow的其他地方看到了與此相關的顯然相關的問題,但答案對於低腦瓦數的XSLT初學者來說有點令人費解。用於顯示行中元素的XSLT

基本上我試圖從我的XML在整個頁面的列中顯示項目。我現在只想做2列,但我希望有一個解決方案,其中列數不是硬編碼的。

我的XML數據是這樣的,大約有100個節點:

<?xml version="1.0" encoding="UTF-8"?> 
    <response> 
     <node type="category"> 
      <collection> 
       <node> 
        <articleId>1</articleId> 
        <headline>Merry Christmas says Google as it unveils animated Jingle Bells Doodle</headline> 
       </node> 
       <node> 
        <articleId>2</articleId> 
        <headline>Google activating 700,000 Android phones every day</headline> 
       </node> 
       <node> 
        <articleId>3</articleId> 
        <headline>Google attacked by music industry over 'broken pledges' on illegal downloading</headline> 
       </node> 
      </collection> 
     </node> 
    </response> 

我想翻譯成這樣的事情:

<div> 
     <div class="left"> 
      [ the articleId ] 
      [ the headline ] 
     </div> 
     <div class="right"> 
      [ the articleId ] 
      [ the headline ] 
     </div> 
    </div> 

與左邊的第1條,第2條對我們試圖XSLT的權利,其下一行的第3條左側,等等,等等

這樣

<xsl:for-each select="$collection/spi:node[(position() mod $columns) != 0]"> 
<xsl:variable name="pos" select="position()"/> 
<xsl:variable name="node" select="."/> 
<div> 
    <div class="left"> 
     <xsl:value-of select="../spi:node[$pos]/spi:articleId"/>] 
     <xsl:value-of select="../spi:node[$pos]/spi:headline"/> 
    </div> 
    <div class="right"> 
     <xsl:value-of select="../spi:node[$pos + 1]/spi:articleId"/> 
     <xsl:value-of select="../spi:node[$pos + 1]/spi:headline"/> 
    </div> 
</div> 
</xsl:for-each> 

但是,這隻會導致空白的div和怪異的文章重複。任何XSLT大師都可以指引我們走向正確的方向嗎?

乾杯

回答

1

如果你寫你的$ POS變量的值,你會發現它變爲1,2,3 ...等,而不是1,3,...這是你可能期待的。這就是爲什麼你會得到重複,我想。

其實,沒有必要尋找使用$ POS變量節點,因爲你已經被定位於對每次第一個節點上,因此,所有你需要做的是什麼這樣

<xsl:for-each select="$collection/spi:node[(position() mod $columns) != 0]"> 
    <div> 
     <div class="left"> 
      <xsl:value-of select="articleId"/> 
      <xsl:value-of select="headline"/> 
     </div> 
     <div class="right"> 
      <xsl:value-of select="following-sibling::spi:node[1]/articleId"/> 
      <xsl:value-of select="following-sibling::spi:node[1]/headline"/> 
     </div> 
    </div> 
    </xsl:for-each> 

待辦事項,它通常是用XSL最佳實踐:應用模板,而不是的xsl:for-每個,所以你可以把它重新寫這樣的:

<xsl:template match="/"> 
    <xsl:variable name="collection" select="response/node/collection"/> 
    <xsl:apply-templates 
     select="$collection/spi:node[(position() mod $columns) != 0]" mode="group"/> 
</xsl:template> 

<xsl:template match="node" mode="group"> 
    <div> 
     <div class="left"> 
     <xsl:call-template name="spi:node"/> 
     </div> 
     <div class="right"> 
     <xsl:apply-templates select="following-sibling::spi:node[1]"/> 
     </div> 
    </div> 
</xsl:template> 

<xsl:template name="node" match="node"> 
    <xsl:value-of select="articleId"/> 
    <xsl:value-of select="headline"/> 
</xsl:template> 
+0

非常感謝Tim,很好的回答! – 2012-02-13 16:37:38