2009-11-06 43 views
2

我在下面的格式,我要重新格式化XML:XSLT/Xpath的:選擇前面的評論

<blocks> 
    <!-- === apples === --> 
    <block name="block1"> 
     ... 
    </block> 
    <!-- === bananas === --> 
    <block name="block2"> 
     ... 
    </block> 
    <!-- === oranges === --> 
    <block name="block3"> 
     ... 
    </block> 
</blocks> 

我的問題是我無法弄清楚如何選擇每塊標記上述評論。我有以下XSL:

<xsl:template match="//blocks"> 
     <xsl:apply-templates select="block" /> 
</xsl:template> 
<xsl:template match="block"> 
    <xsl:apply-templates select="../comment()[following-sibling::block[@name = ./@name]]" /> 
    <xsl:value-of select="./@name" /> 
</xsl:template> 
<xsl:template match="comment()[following-sibling::block]"> 
    <xsl:value-of select="."></xsl:value-of> 
</xsl:template> 

,我想對輸出結果是:

===蘋果===
塊1
===香蕉===
塊2
===橘子===
塊3

但我能得到最好的是:

===蘋果===
===香蕉===
===橘子===
塊1
===蘋果===
===香蕉===
===橘子===
塊2
===蘋果===
===香蕉===
===橘子===
塊3

我一個如果這有什麼不同,請使用PHP。

回答

0

您也可以在第一個應用程序模板而不是第二個應用程序模板中應用註釋模板,以便它按順序發生 - 此外,此解決方案依賴於源xml中數據的順序..

<xsl:template match="//blocks"> 
     <xsl:apply-templates select="block | comment()" /> 
</xsl:template> 

PS: - 您可以避免在表達式中使用「//」,因爲它可能不是最佳選擇。

[編輯] 完整的樣式表

<?xml version="1.0"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:template match="//blocks"> 
    <xsl:apply-templates select="block | comment()"/> 
</xsl:template> 
<xsl:template match="block"> 
    <xsl:value-of select="./@name"/> 
</xsl:template> 
<xsl:template match="comment()"> 
    <xsl:value-of select="."/> 
</xsl:template> 
</xsl:stylesheet> 

添加以下語句,如果你想換行,打印在兩個塊和評論的價值之後。

<xsl:text>&#10;</xsl:text> 
+0

謝謝,我更喜歡你的版本,這似乎更簡單。很棒。 –

3

您的樣式表有些過於複雜。

你應該試試下面的樣式表,你會發現它匹配你想要的輸出!

<xsl:template match="//blocks"> 
     <xsl:apply-templates select="block" /> 
</xsl:template> 
<xsl:template match="block"> 
    <xsl:apply-templates select="preceding-sibling::comment()[1]" /> 
    <xsl:value-of select="./@name" /> 
</xsl:template> 
<xsl:template match="comment()"> 
    <xsl:value-of select="."></xsl:value-of> 
</xsl:template> 

此代碼始終匹配1個或0個註釋,該註釋始於當前塊標記之前。

+0

謝謝,這個工程。複雜樣式表的原因是我使用的實際XML在其他地方也有註釋,我也試圖避免匹配它們。 –