【问题标题】:Python XML ElementTree - findallPython XML ElementTree - findall
【发布时间】:2020-04-01 13:59:47
【问题描述】:

我正在处理 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】:

    您可以使用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') 会让你所有的 &lt;query&gt; 元素从根节点开始搜索
    • type_tag.findall('./where/condition') 将获取当前查询 tpye_tag 中的所有 &lt;condition&gt; 元素

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-26
      • 1970-01-01
      • 1970-01-01
      • 2015-10-16
      • 1970-01-01
      • 1970-01-01
      • 2016-04-30
      • 1970-01-01
      相关资源
      最近更新 更多