从lxml中选择属性值

时间:2011-05-25 15:16:18

标签: python 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: '@'

我希望这可行吗?

2 个答案:

答案 0 :(得分:52)

XPath的

findfindall only implement a subset。它们的存在旨在提供与其他ElementTree实现的兼容性(如ElementTreecElementTree)。

相反,xpath方法提供对XPath 1.0的完全访问权限:

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

但是,您可以使用get

print customer.get('NAME')

attrib

print customer.attrib['NAME']

答案 1 :(得分:0)

作为可能有用的补充,这是在元素具有多个元素的情况下如何获取属性的值,并且这是相对于另一个元素的唯一区别。 例如,给定以下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]
相关问题