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:


<?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(“/route/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

With Python it is quite easy to read XML files.