The limit of Element Tree on xpath

a 夏天 提交于 2019-12-08 02:04:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!