當前所選的溶液:
//comment()/following-sibling::*[1]/self::item
不會在存在一個處理。第指令(或整組處理指令)的註釋和元件之間的情況下工作 - 正如Martin Honnen在評論中注意到的那樣。
下面的解決方案不存在這樣的問題。
下面的XPath表達式選擇,它們或者立即由註釋節點之前,或者是緊接在空白僅文本節點,該節點立即被註釋節點之前先只元素節點:
(//comment()
/following-sibling::node()
[1]
[self::text()
and
not(normalize-space())
]
/following-sibling::node()
[1] [self::item]
)
|
(//comment()
/following-sibling::node()
[1]
[self::item]
)
這是一個完整的測試:
我們用這個XML文檔:
<root>
<list>
<!-- foo's comment -->
<item name="foo" />
<item name="bar" />
<!-- another foo's comment -->
<item name="another foo" />
<!-- comment 3 --><item name="immed.after 3"/>
<!-- comment 4 --><?PI ?><item name="after PI"/>
</list>
</root>
當以下變換被施加在上面的XML文檔:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/">
<xsl:copy-of select=
"
(//comment()
/following-sibling::node()
[1]
[self::text()
and
not(normalize-space())
]
/following-sibling::node()
[1] [self::item]
)
|
(//comment()
/following-sibling::node()
[1]
[self::item]
)
"/>
</xsl:template>
</xsl:stylesheet>
有用,正確的結果產生:
<item name="foo"/>
<item name="another foo"/>
<item name="immed.after 3"/>
注意,在XSLT/XPath數據模型的那些項目元素你正在尋找一個不是立即在註釋節點之前,而是在一個空白的文本節點之前。 因此,除非在樣式表中使用'',否則這些空白文本節點可能會妨礙您的使用。 –
2010-04-10 12:32:07
好問題(+1)。請參閱我的答案,瞭解唯一(目前)完整的解決方案。 Martin Honnen的評論是正確的,儘管當前選定的答案可能適用於您,但它可能會突然停止這樣做(如果XPath引擎提供了XML文檔,其空白節點沒有被剝離)。 – 2010-04-10 16:08:13