2016-12-29 116 views
0

這是HTML:XSLT:重複一個節點與每個順序節點

<html> 
    <div> 
     <div class="theheader">The first header</div> 
    </div> 
    <div class="thecontent"> 
     <div class="col1">Col 1 </div> 
     <div class="col2">Col 2 </div> 
    </div> 
    <div class="thecontent"> 
     <div class="col1">Col 3 </div> 
     <div class="col2">col 4 </div> 
    </div> 
    <div> 
     <div class="theheader">The second header</div> 
    </div> 
    <div class="thecontent"> 
     <div class="col1">Col 5 </div> 
     <div class="col2">Col 6 </div> 
    </div> 
    <div class="thecontent"> 
     <div class="col1">Col 7 </div> 
     <div class="col2">Col 8 </div> 
    </div> 
</html> 

這是XSL:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output method="text" encoding="utf-8" omit-xml-declaration="yes" indent="no"/> 

    <xsl:template match="div[@class='theheader']" /> 

    <xsl:template match="div[@class='thecontent']"> 
     <xsl:value-of select="//div[@class='theheader']" /><xsl:text>: </xsl:text> 
     <xsl:value-of select="." /> 
     <xsl:text>&#10;</xsl:text> 
    </xsl:template> 

</xsl:stylesheet> 

這是輸出:

The first header: Col 1 Col 2 
The first header: Col 3 col 4 
The first header: Col 5 Col 6 
The first header: Col 7 Col 8 

希望的輸出:

The first header: Col 1 Col 2 
The first header: Col 3 col 4 
The second header: Col 5 Col 6 
The second header: Col 7 Col 8 

怎麼辦? XSLT 1.0首選。

還試圖:(之前的點//)

<xsl:value-of select=".//div[@class='theheader']" /><xsl:text>: </xsl:text> 

和無報頭被輸出。誰能告訴我爲什麼? 編輯示例是因爲第一版過於簡化。現在SO告訴我這是太多的代碼。希望這個盈餘文字有幫助。

回答

3

你需要的代碼的頭球模板匹配「theheader」移動到輸出到模板匹配「thecontent」來代替,因此它是重複的。您還需要使用preceding-sibling軸來獲得您需要的div。

試試這個XSLT

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output method="text" encoding="utf-8" omit-xml-declaration="yes" indent="no"/> 

    <xsl:template match="div[@class='theheader']" /> 

    <xsl:template match="div[@class='thecontent']"> 
     <xsl:value-of select="preceding-sibling::div[div/@class='theheader'][1]/div" /><xsl:text>: </xsl:text> 
     <xsl:for-each select="div"> 
      <xsl:value-of select="." /> 
     </xsl:for-each> 
     <xsl:text>&#10;</xsl:text> 
    </xsl:template> 

</xsl:stylesheet> 

編輯:在回答你關於深theheader可能是多層次的評論,請嘗試以下表現之一,而不是

<xsl:value-of select="preceding-sibling::div[descendant::div/@class='theheader'][1]//div[@class='theheader']" /> 

<xsl:value-of select="preceding::div[@class='theheader'][1]" /> 
+0

感謝。這有效,但我簡單地說明了我的例子。現在改寫了。希望你可以看看新版本。 – Peter

+0

@Peter:您希望XSLT在有標題但沒有內容時表現如何?只是檢查您的邊緣案例的要求... – JohnLBevan

+0

不錯的觀察約翰。內容有保證。 – Peter