从 lxml 选择属性值
我想使用 xpath 表达式来获取属性的值。
我期望以下内容能够工作
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: '@'
我期望它能够工作是错误的吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
find
和findall
仅实现XPath 的子集。它们的存在旨在提供与其他 ElementTree 实现(如 ElementTree 和 cElementTree )的兼容性。相比之下,
xpath
方法提供对 XPath 1.0 的完全访问:但是,您也可以使用
get
:或
attrib
:find
andfindall
only implement a subset of XPath. Their presence is meant to provide compatibility with other ElementTree implementations (likeElementTree
andcElementTree
).The
xpath
method, in contrast, provides full access to XPath 1.0:However, you could instead use
get
:or
attrib
:作为一个可能有用的补充,这是在元素具有多个属性的情况下如何获取属性的值,并且这是相对于另一个元素的唯一区别。
例如,给定以下 file.xml:
可以通过以下方式访问属性“bar”:
As a possible useful addition, this is how to get the value of an attribute in the case that the element has more than one, and it is the only difference with respect to another element.
E.g., given the following file.xml:
One can access the attribute 'bar' with: