I want to use an xpath expression to get the value of an attribute.
I expected the following to work
JavaScript
x
5
1
from lxml import etree
2
3
for customer in etree.parse('file.xml').getroot().findall('BOB'):
4
print customer.find('./@NAME')
5
but this gives an error :
JavaScript
1
12
12
1
Traceback (most recent call last):
2
File "bob.py", line 22, in <module>
3
print customer.find('./@ID')
4
File "lxml.etree.pyx", line 1409, in lxml.etree._Element.find (src/lxml/lxml.etree.c:39972)
5
File "/usr/local/lib/python2.7/dist-packages/lxml/_elementpath.py", line 272, in find
6
it = iterfind(elem, path, namespaces)
7
File "/usr/local/lib/python2.7/dist-packages/lxml/_elementpath.py", line 262, in iterfind
8
selector = _build_path_iterator(path, namespaces)
9
File "/usr/local/lib/python2.7/dist-packages/lxml/_elementpath.py", line 246, in _build_path_iterator
10
selector.append(ops[token[0]](_next, token))
11
KeyError: '@'
12
Am I wrong to expect this to work?
Advertisement
Answer
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:
JavaScript
1
2
1
print customer.xpath('./@NAME')[0]
2
However, you could instead use get
:
JavaScript
1
2
1
print customer.get('NAME')
2
or attrib
:
JavaScript
1
2
1
print customer.attrib['NAME']
2