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.
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"?> <students> <student id="1"> <name>Student one</name> <email>Student1@gmail.com</email> <mobile>9029049420</mobile> </student> <student id="2"> <name >Student Two</name> <email>Student2@gmail.com</email> <mobile>8049049420</mobile> </student> </students>
in python file we first need to add the reference of minidom using from xml.dom import minidom
statement.
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 path=os.getcwd() url =path+ "\\testdata\\student-data.xml" #print(url) # 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] print(sid,name.firstChild.data, email.firstChild.data)
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