2011-05-25 90 views
27

我想使用xpath表達式來獲取屬性的值。從lxml中選擇屬性值

我希望下面的工作

from lxml import etree 

for customer in etree.parse('file.xml').getroot().findall('BOB'): 
    print customer.find('./@NAME') 

但是這給出了一個錯誤:

Traceback (most recent call last): 
    File "bob.py", line 22, in <module> 
    print customer.find('./@ID') 
    File "lxml.etree.pyx", line 1409, in lxml.etree._Element.find (src/lxml/lxml.etree.c:39972) 
    File "/usr/local/lib/python2.7/dist-packages/lxml/_elementpath.py", line 272, in find 
    it = iterfind(elem, path, namespaces) 
    File "/usr/local/lib/python2.7/dist-packages/lxml/_elementpath.py", line 262, in iterfind 
    selector = _build_path_iterator(path, namespaces) 
    File "/usr/local/lib/python2.7/dist-packages/lxml/_elementpath.py", line 246, in _build_path_iterator 
    selector.append(ops[token[0]](_next, token)) 
KeyError: '@' 

我錯了期待這個工作?

回答

37

findfindallonly implement a subset XPath。他們的存在意在提供與其他ElementTree實現(如ElementTreecElementTree)的兼容性。

xpath方法,相反,提供了完全訪問的XPath 1.0:

print customer.xpath('./@NAME')[0] 

但是,你也可以使用get

print customer.get('NAME') 

attrib

print customer.attrib['NAME'] 
+6

正確,但是如果你想要「正式」的首選方式:使用'customer.get('NAME ')'(參見http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.attrib) – Steven 2011-05-25 18:49:40