Python XML ElementTree-findall

问题描述 投票:0回答:1

我正在使用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。例如,它将打印我:

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'])

但是我不知道如何同时做这两项。

任何评论都会有所帮助!

祝您有美好的一天:)

python python-3.x xml xml-parsing elementtree
1个回答
0
投票

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

for type_tag in myroot.findall('./query'):
    print(type_tag.attrib['label'])
    for e in type_tag.findall('./where/condition'):
        print(e.attrib['expr'])

# nom1
# expression1
# nom2
# expression2

说明:

  • [myroot.findall('./query')将使您所有的<query>元素都从根节点开始搜索
  • [type_tag.findall('./where/condition')将使您获得当前查询<condition>中的所有tpye_tag个元素
© www.soinside.com 2019 - 2024. All rights reserved.