Parse XML file in python and retrieve nested children

This post has everything of a duplicate.. and yet I can not figure it out despite the dozen of posts I’ve read.

Here is the XML (a short version):

<?xml version="1.0" encoding="iso-8859-1" standalone="yes" ?>
<coordinates xmlns="" xmlns:xsi="">
        <name>HydroCel GSN 256 1.0</name>
    <acqMethod>An Average of Many Data Sets&#x09;&#x09;&#x09;&#x09;</acqMethod>

How can I retrieve a list of sensors with the name, number, and coordinates for each sensor?

I am struggling to iterate over this tree:

tree = ET.parse(xml_fname)
root = tree.getroot()

# And then what?
# root.iter("sensor")  does not yield any element
# root.find("sensor")  returns None
# and so on...

The tag of the root looks weird to me..


Thanks for the help!

>Solution :

You can just parse it with namespace support. See below.

from xml.etree import ElementTree as ET
root = ET.parse(xml_fname)
# Use an XPath to get all sensor tags
sensors = root.findall(".//sensorLayout/sensors/sensor", namespaces={"": ""})
# Burst values from each child of every sensor
sensor_values = [{ct.tag.split("}")[-1]: ct.text for ct in sensor.getchildren()} for sensor in sensors]
# Dict key is formed by removing the namspace part in the tag - dirty!

You get something lik e

{'name': None, 'number': '1', 'type': '0', 'x': '6.962', 'y': '5.382', 'z': '-2.191'}, 
{'name': None, 'number': '2', 'type': '0', 'x': '6.484', 'y': '6.404', 'z': '-0.140'}, 
{'name': None, 'number': '3', 'type': '0', 'x': '5.699', 'y': '7.208', 'z': '1.791'}

Leave a Reply