【问题标题】:How to query XML node using ElementTree in python如何在 python 中使用 ElementTree 查询 XML 节点
【发布时间】:2016-08-17 08:17:34
【问题描述】:

我有以下示例 XML 树:

<main>
  <section>
     <list key="capital" value="sydney">
        <items>
           <item id="abc-123"></item>
           <item id="abc-345"></item>
        </items>
     </list>
     <list key="capital" value="tokyo">
        <items>
           <item id="def-678"></item>
           <item id="def-901"></item>
        </items>
     </list>
  </section>
</maim>

您知道如何运行一个查询,该查询将提取“list”下的 key="capital" 和 value="tokyo" 的“items”节点(应该提取 id="def-678" 和id="def-901")?

非常感谢您的帮助!

【问题讨论】:

    标签: python xml extract elementtree


    【解决方案1】:

    您可以通过find()findall() 方法使用xml.etree 支持的XPath 表达式(参见the documentation):

    from xml.etree import ElementTree as ET
    
    raw = '''your xml string here'''
    root = ET.fromstring(raw)
    result = root.findall(".//list[@key='capital'][@value='tokyo']/items/item")
    

    控制台测试输出:

    >>> for r in result:
    ...     print ET.tostring(r)
    ... 
    <item id="def-678" />
    
    <item id="def-901" />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多