Read Data from XML File using Python

test.xml

<?xml version="1.0" encoding="UTF-8"?>
<persons>
    <person id="1">
        <name>John</name>
    </person>
    <person id="2">
        <name>Mary</name>
    </person>
    <person id="3">
        <name>Robert</name>
    </person>
</persons>

xml.etree.ElementTree module

import xml.etree.ElementTree as elementTree

tree = elementTree.parse('test.xml')
root = tree.getroot()

data = []

for person in root:
    data.append({
        'id': int(person.attrib['id']),
        'name': person.findall('name')[0].text
    })

print(data)

Leave a Comment

Cancel reply

Your email address will not be published.