xpath上元素树的限制

nam*_*nam 2 python xml xpath elementtree

我已经使用了Element Tree一段时间了,我喜欢它,因为它简单

但我怀疑它的x路径的实现

这是XML文件

<a>
  <b name="b1"></b>
  <b name="b2"><c/></b>
  <b name="b2"></b>
  <b name="b3"></b>
</a>
Run Code Online (Sandbox Code Playgroud)

python代码

import xml.etree.ElementTree as ET
tree = ET.parse('test.xml')
root = tree.getroot()
root.findall("b[@name='b2' and c]")
Run Code Online (Sandbox Code Playgroud)

该程序显示错误:

invalid predicate
Run Code Online (Sandbox Code Playgroud)

但是,如果我使用

root.findall("b[@name='b2']") or 
 root.findall("b[c]")
Run Code Online (Sandbox Code Playgroud)

有用,

Fre*_*Foo 5

ElementTree为XPath表达式提供有限的支持.目标是支持缩写语法的一小部分; 完整的XPath引擎不在核心库的范围内.

(F. Lundh,ElementTree中的XPath支持.)

对于支持XPath(1.0)的ElementTree实现,请查看LXML:

>>> s = """<a>
  <b name="b1"></b>
  <b name="b2"><c /></b>
  <b name="b2"></b>
  <b name="b3"></b>
</a>"""
>>> from lxml import etree
>>> t = etree.fromstring(s)
>>> t.xpath("b[@name='b2' and c]")
[<Element b at 1340788>]
Run Code Online (Sandbox Code Playgroud)