Python - How to read XML file

By xngo on June 12, 2019

The XML file

Create a simple XML file, e.g. countries.xml.

<?xml version="1.0"?>
<data>
    <country name="Singapore">
        <rank>4</rank>
        <year>2017</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank>68</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>

Parsing XML file

This short tutorial uses xml.etree.ElementTree to parse through the XML file.

#!/usr/bin/python3
 
import xml.etree.ElementTree as ET
 
tree = ET.parse('countries.xml')
 
# Get the root element.
root = tree.getroot()
 
# Every element has a tag and an attribute.
print("Tag name =", root.tag, "|", "Attribute = ", root.attrib)
 
# Iterate over the children of an element, i.e. root.
for child in root:
    print(child.tag, child.attrib)
 
# You can directly access the child element using index.
country=root[1]     # <country name="Panama">
print(country.get('name'))
 
year=root[1][1]     # <year>2011</year>
print(year.text)
 
neighbor=root[1][3] # <neighbor name="Costa Rica" direction="W"/>
print(neighbor.get('direction'))

Result of reading the XML file

Reference

  • https://docs.python.org/3.7/library/xml.etree.elementtree.html

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.