2012-06-11 70 views
2

我用元素树了一段时间,我喜欢它,因为它的简单的限元素树的XPath的

但我怀疑它的实现路径X

的这是XML文件

<a> 
    <b name="b1"></b> 
    <b name="b2"><c/></b> 
    <b name="b2"></b> 
    <b name="b3"></b> 
</a> 

的Python代码

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

该程序显示了错误:

invalid predicate 

但是,如果使用

root.findall("b[@name='b2']") or 
root.findall("b[c]") 

它的工作原理,

回答

5

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

对于支持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>] 
+0

谢谢,好吧,您认为lxml必须是下一个版本而不是元素树的python核心的一部分吗? – nam

+0

@HOAINAMNGUYEN:我不认为:) –

+0

@nam:不,它不会 – hoju

3

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.

你刚刚在发现的限制实施。您可以改用lxml;它提供了一个完整的XPath 1.0 support ElementTree兼容接口。