Read XML data in Python Example

Here you learn how to work with XML data in python code, we often read XML document in python programming, load xml document or read from xml string, let’s learn with example.

We need to import minidom library in our python code.

python xml example

In this example we try to read following xml document in our python code.

Notice, in following document we have attributes and child tag, so we can learn how to deal with those values in python code.

<?xml version="1.0" encoding="UTF-8"?>
    <student id="1">
        <name>Student one</name>
	 <student id="2">
        <name >Student Two</name>

in python file we first need to add the reference of minidom using from xml.dom import minidom statement.

Reading xml document in python code

Make sure you have set the file path correctly, to get the folder root we can use path=os.getcwd()

from xml.dom import minidom
import os

#execute : pip install lxml
url =path+ "\\testdata\\student-data.xml"

# parse an xml file by name
mydoc = minidom.parse(url)

students = mydoc.getElementsByTagName('student')

for stu in students:
    sid = stu.getAttribute("id")
    name = stu.getElementsByTagName("name")[0]
    email = stu.getElementsByTagName("email")[0]

if you notice in above code, to read the value from xml attribute, we have used getAttribute method stu.getAttribute("id"). and to read value from xml child tag we have used stu.getElementsByTagName("name")[0].

You may be interested to read following tutorials

Read XML Python
Python XML example
Python programming examples | Join Python Course