我有一个 XML 文档,其中的片段行可能如下所示:
<p>Some text <!--a comment --> some more text <b>some bold text</b> something else etc</p>
我想根据其文本以及所有以下“同级”元素来选择评论。在这个例子中,我知道我可以用'//comment()[获得评论。 =“一条评论”]'。
如何获得结果:“更多文本一些粗体文本其他内容等”? (段落标记内的其余 sibling )
如果有什么不同,我使用 python 和 etree 来解析。
编辑:
我的完整测试 XML:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<p>A paragraph<!--A comment--><b>test</b>A line break</p>
</root>
我的测试 XSLT:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:template match="/">
<xsl:copy-of select='//comment()/following-sibling::node()'/>
</xsl:template>
</xsl:stylesheet>
结果:
<?xml version="1.0" encoding="UTF-8"?>
或者,在 Python 中,使用 lxml,只是一个“None”对象。
编辑#2:
我的错——接受的答案效果很好!
最佳答案
如果您想获取所有 sibling ,包括其他评论:
//comment()[.="a comment "]/following-sibling::node()
例如:
>>> xml.xpath('//comment()[.="a comment "]/following-sibling::node()')
[' some more text ', <Element b at 0x2923af0>, ' ', <!-- other comment -->, ' something else etc']
我添加了一条附加评论,但使用了您的输入数据。
关于python - 选择xpath中注释的所有兄弟(包括文本),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21050732/