我想获取所有具有属性 x 的元素,包括根节点。我目前所拥有的是它可以工作,只是它不包括根节点。从打印输出中可以看到,它选择了 B 和 Ca 元素。但是,输出还应包括 A,即 [元素 A、元素 B、元素 Ca]。我怎样才能让它也捕获根节点?
from lxml import etree as ET
expr='''
<A x="1">
<B z="1">
<C y="1"/>
</B>
<B x="1">
<Ca x="1" y="2"/>
</B>
</A>
'''
expr_root=ET.fromstring(expr)
print(expr_root.findall(".//*[@x]")) #[<Element B at 0xd0118c8>, <Element Ca at 0xd011b48>]
最佳答案
您可以使用descendant-or-self
:
expr_root.xpath(".//descendant-or-self::*[@x]")
演示:
In [1]: from lxml import etree as ET
In [2]: expr = '''
...: <A x="1">
...: <B z="1">
...: <C y="1"/>
...: </B>
...: <B x="1">
...: <Ca x="1" y="2"/>
...: </B>
...: </A>
...: '''
In [3]: expr_root = ET.fromstring(expr)
In [4]: print(expr_root.xpath(".//descendant-or-self::*[@x]"))
[<Element A at 0x1045675c8>, <Element B at 0x105de1688>, <Element Ca at 0x105de0548>]
关于python - XPATH 在 python 中选择具有特定属性的根和所有后代元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43538974/