Parsing XML Document with Python - Search specific Elements, get String inside

60 views Asked by At

I got a XML-Doc with the following structure:

<defaults> 
<options>
<param name="userMail">[email protected]</param>
<param name="adminMail"[email protected]</param>
<param name="language">en</param>
<param name="country">EN</param>
<> ... </> 
</defaults>
</options>

Inside the "options"-Tag I got a lot of param-Elements, I want to search for the "userMail" and "adminMail" element.

    tree = ET.parse("file_config.xml")
    root = tree.getroot()
    for admin in root.iter("param"):
    print(admin.text)

This works great, but I get the whole output ([email protected], admin@mailorg, en, EN).

How can I search only for the "userMail" and "adminMail" element and store each in a single variable?

I use xml.etree.ElementTree as ET.

1

There are 1 answers

0
balderman On BEST ANSWER

See below (do the same for the user mail)

import xml.etree.ElementTree as ET

xml = '''<defaults>
   <options>
      <param name="userMail">[email protected]</param>
      <param name="adminMail">[email protected]</param>
      <param name="language">en</param>
      <param name="country">EN</param>
   </options>
</defaults>'''

root = ET.fromstring(xml)
admin_mail = root.find('.//param[@name="adminMail"]').text
print(admin_mail)

output

[email protected]