首页 > 解决方案 > Python XML ElementTree - findall

问题描述

我正在处理 XML 文件。我的文件是这样的:

import xml.etree.ElementTree as ET

xml = '''
<root>
    <query label="nom1" code="1234">
        <where a="1" b="2">
            <condition id="1534" expr="expression1"/>
        </where>
    </query>
    <query label="nom2" code="2345">
        <where a="2" b="3">
            <condition id="6784" expr="expression2"/>
        </where>
    </query>
</root>
'''

myroot = ET.fromstring(xml)

我想要每个查询的标签和 expr。例如,它将打印 me :

query 1 :
    nom1
    expression1
query 2:
    nom2
    expression2

你知道我该怎么做吗?我知道如何打印所有标签:

for type_tag in myroot.findall('root/query'):
    print(type_tag.attrib['label'])

以及如何打印所有的 expr:

for e in myroot.findall("root/query/.//*[@expr]"):
        print(e.attrib['expr'])

但我不知道如何同时为两者做。

任何评论都会有所帮助!

祝你今天过得愉快 :)

标签: pythonpython-3.xxmlxml-parsingelementtree

解决方案


您可以使用findall()相对于相应元素进行搜索:

for i, type_tag in enumerate(myroot.findall('./query')):
    print(f'query {i+1}:')
    print(type_tag.attrib['label'])
    for e in type_tag.findall('./where/condition'):
        print(e.attrib['expr'])

# query 1:
# nom1
# expression1
# query 2:
# nom2
# expression2

说明:

  • myroot.findall('./query')会让你<query>开始从根节点搜索所有元素
  • type_tag.findall('./where/condition')将为您提供<condition>当前查询中的所有元素tpye_tag

推荐阅读