Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
482 views
in Technique[技术] by (71.8m points)

python - selecting attribute values from lxml

I want to use an xpath expression to get the value of an attribute.

I expected the following to work

from lxml import etree

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

but this gives an error :

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: '@'

Am I wrong to expect this to work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

find and findall only implement a subset of XPath. Their presence is meant to provide compatibility with other ElementTree implementations (like ElementTree and cElementTree).

The xpath method, in contrast, provides full access to XPath 1.0:

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

However, you could instead use get:

print customer.get('NAME')

or attrib:

print customer.attrib['NAME']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...