【问题标题】:XPath Query in XML using Python使用 Python 在 XML 中进行 XPath 查询
【发布时间】:2010-11-21 14:33:38
【问题描述】:

在处理 XML 时是否可以在 Python 中使用 XPath 查询。我正在使用不支持该功能的 minidom。还有其他模块吗?

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    我最喜欢的 Python XML 处理库是 lxml,因为它是 libxml2 的包装器,所以也支持完整的 XPath。

    还有4Suite,它更像是一个纯 Python 解决方案。

    【讨论】:

      【解决方案2】:

      http://docs.python.org/library/xml.etree.elementtree.html

      etree 支持 XPath 查询,就像 lxml。

      etree 包含在标准库中,但 lxml 更快。

      【讨论】:

      • ElementTree 对 XPath 的支持有限,正如 Python 3 docs 中所引用的那样:“该模块为 XPath 表达式提供了有限的支持,用于在树中定位元素。目标是支持一小部分缩写语法;完整的 XPath 引擎超出了模块的范围。"
      【解决方案3】:

      包含元素树。在 2.6 及以下它的 xpath 非常弱,但在 2.7 much improved:

      import xml.etree.ElementTree as et
      root = et.parse(filename)
      result = ''
      
      # How to make decisions based on attributes even in 2.6
      for e in root.findall('.//child/grandchild'):
          if e.attrib.get('name') == 'foo':
              result = e.text
              break
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-07-18
        • 2019-12-14
        • 2019-10-30
        • 2010-09-18
        • 1970-01-01
        • 2014-05-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多