2012-06-11 71 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兼容接口。