mathilde
mathilde

Reputation: 204

Python XML ElementTree - findall

I'm working with XML files. My file is like that :

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)

I want to have the label and the expr for each query. For example, it will print me :

query 1 :
    nom1
    expression1
query 2:
    nom2
    expression2

Do you know how can I do that ? I know how to print all the label:

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

And how to print all the expr:

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

But I don't know how to do for both in the same time.

Any comment will be helpful !

Have a nice day :)

Upvotes: 0

Views: 3158

Answers (1)

AnsFourtyTwo
AnsFourtyTwo

Reputation: 2528

You can use findall() to search relative to the respective element:

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

Explanations:

  • myroot.findall('./query') will get you all <query> elements beginning to search from the root node
  • type_tag.findall('./where/condition') will get you all <condition> elements within the current query tpye_tag

Upvotes: 3

Related Questions