61

我想使用 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: '@'

我期望这行得通是错的吗?

4

2 回答 2

81

find并且findall 只实现XPath 的一个子集。它们的存在旨在提供与其他 ElementTree 实现(如ElementTreecElementTree)的兼容性。

xpath相比之下,该方法提供对 XPath 1.0 的完全访问:

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

但是,您可以改为使用get

print customer.get('NAME')

attrib

print customer.attrib['NAME']
于 2011-05-25T15:19:57.020 回答
1

作为一个可能有用的补充,这是在元素有多个的情况下如何获取属性的值,这是与另一个元素的唯一区别。例如,给定以下 file.xml:

<?xml version ="1.0" encoding="UTF-8"?>
    <level1>
      <level2 first_att='att1' second_att='foo'>8</level2>
      <level2 first_att='att2' second_att='bar'>8</level2>
    </level1>

可以通过以下方式访问属性“bar”:

import lxml.etree as etree
tree = etree.parse("test_file.xml")
print tree.xpath("//level1/level2[@first_att='att2']/@second_att")[0]
于 2020-10-07T13:55:10.977 回答