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"?>
    <country name="Singapore">
        <neighbor name="Malaysia" direction="N"/>
    <country name="Panama">
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>

Parsing XML file

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

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">
year=root[1][1]     # <year>2011</year>
neighbor=root[1][3] # <neighbor name="Costa Rica" direction="W"/>

Result of reading the XML file



About the author

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