【问题标题】:selecting attribute values from lxml从 lxml 中选择属性值
【发布时间】:2011-09-01 21:03:52
【问题描述】:

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

我期望这会起作用吗?

【问题讨论】:

    标签: python python-2.7 attributes lxml


    【解决方案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]
    

    【讨论】:

      【解决方案2】:

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

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

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

      但是,您可以改用 get:

      print customer.get('NAME')
      

      attrib:

      print customer.attrib['NAME']
      

      【讨论】:

      • 正确,但如果您想要“官方”首选方式:使用customer.get('NAME')(请参阅docs.python.org/library/…
      • 所以没有直接的获取价值的方法!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-09
      相关资源
      最近更新 更多