选择 xpath 中注释的所有同级(包括文本)



我有一个XML文档,其片段行可能如下所示:

<p>Some text <!--a comment --> some more text <b>some bold text</b> something else etc</p>

我想根据其文本以及所有以下"兄弟姐妹"元素选择评论。在这个例子中,我知道我可以用'//comment()[. = "a comment"]'来获取注释。

我怎样才能得到结果:"更多文本一些粗体文本其他内容等"?(段落标签内的其余兄弟姐妹)

万一有任何区别,我正在使用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:

我的错 - 接受的答案效果很好!

如果您想获取所有兄弟姐妹,包括其他注释:

//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']

我添加了一条额外的评论,但以其他方式使用了您的输入数据。

最新更新