Read XML file in Python

Read XML file in Python is very easy, the file that we will use for reading in this example is the following:

ยป More Python Examples


<?xml version="1.0"?>
 <employee id="1">
 <name>Jackson Aiden</name>
 <employee id="2">
 <name>Emma Sophia</name>

We import minidom.

from xml.dom import minidom

doc = minidom.parse("/path/data.xml")

name = doc.getElementsByTagName("name")[0]

employees = doc.getElementsByTagName("employee")
for employee in employees:
    sid = employee.getAttribute("id")
    username = employee.getElementsByTagName("username")[0]
    password = employee.getElementsByTagName("password")[0]
    print("id:%s " % sid)
    print("username:%s" %
    print("password:%s" %

To start the parsing we use: doc = minidom.parse(“/path/data.xml”).

It is possible to find any node of the document as we do in the line with the function name = doc.getElementsByTagName(“name”)[0].

Get a list of nodes and their attributes: sid = employee.getAttribute(“id”).

Or get other nodes and their respective text content: username = employee.getElementsByTagName(“username”)[0].

With which you will get something like this:

Read XML file in Python

We hope this example of read an XML file in Python will help you.