[SOLVED] Python ElementTree – getting element with specific attribute


I have some XML where each element has slightly different attributes. I only want to pull the element with the population attribute. The below code works. However, if I uncomment the population assignment and print at the bottom, it fails because the population attribute is not in the first two elements. How do I only select the element with that specific attribute? It’s the only one I need anyway.

from xml.etree import ElementTree as ET

xml = '''<?xml version="1.0"?>
    <country name="Liechtenstein">
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    <country name="Singapore">
        <neighbor name="Malaysia" direction="N"/>
    <country name="Panama">
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E" population="500"/>

root = ET.fromstring(xml)

for target in root.findall('.//country'):
    name = target.attrib['name']
    #population = target.attrib['population']


In the code you are looking for country elements with a population attribute, but there are no such elements.

To get any element with a population attribute, you can use a wildcard for the element name:

for target in root.findall('.//*[@population]'):
    print(target.tag, target.attrib)


neighbor {'name': 'Colombia', 'direction': 'E', 'population': '500'}

Answered By – mzjn

Answer Checked By – Marilyn (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.