问题
I've used Element Tree for a while and i love it because of its simplicity
But I'm doubting of its implementation of x path
This is the XML file
<a>
<b name="b1"></b>
<b name="b2"><c/></b>
<b name="b2"></b>
<b name="b3"></b>
</a>
The python code
import xml.etree.ElementTree as ET
tree = ET.parse('test.xml')
root = tree.getroot()
root.findall("b[@name='b2' and c]")
The program shows the error:
invalid predicate
But if I use
root.findall("b[@name='b2']") or
root.findall("b[c]")
It works,
回答1:
ElementTree provides limited support for XPath expressions. The goal is to support a small subset of the abbreviated syntax; a full XPath engine is outside the scope of the core library.
(F. Lundh, XPath Support in ElementTree.)
For an ElementTree implementation that supports XPath (1.0), check out 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>]
回答2:
From the ElementTree documentation on XPath support.:
ElementTree provides limited support for XPath expressions. The goal is to support a small subset of the abbreviated syntax; a full XPath engine is outside the scope of the core library.
You've just discovered a limitation in the implementation. You could use lxml instead; it provides a ElementTree-compatible interface with complete XPath 1.0 support.
来源:https://stackoverflow.com/questions/10982557/the-limit-of-element-tree-on-xpath