Know more about Python XML Parser

Python XML minidom and ElementTree module

The Python XML module support two sub-modules minidom and ElementTreeto parse an XML record in Python.

XML File

For every one of the models in this instructional exercise, we will utilize the demo.xmlfile, which contains the accompanying XML information:

<phone>(080) 78168241</phone>
<country>South Africa</country>

<phone>(026) 53458662</phone>

<phone>(051) 96790901</phone>

<phone>(014) 98829753</phone>
<country>Korea, South</country>
  1. <phone>,
  2. <email>, and
  3. <country>

Parse/Read XML Document in Python using minidom

minidom is the submodule of the Python standard XML module, which means you do not have to pip install XML to use minidom.

from xml.dom import minidom  minidom.parse("filename")
from xml.dom import minidom

#parse xml file
file = minidom.parse('demo.xml')

#grab all <record> tags
records = file.getElementsByTagName("record")


for record in records:
#access <name> and <phone> node of every record
name = record.getElementsByTagName("name")
phone = record.getElementsByTagName("phone")

#access data of name and phone
print(name[0], end="----->")
Jameson----->(080) 78168241
Colton----->(026) 53458662
Dillon----->(051) 96790901
Channing----->(014) 98829753

Parse/Read XML Document in Python Using ElementTree

The ElementTree module gives a basic and direct approach to parse and peruse XML documents in Python. As minidom is the submodule of xml.dom, the ElementTree is the submodule of xml.etree.

import xml.etree.ElementTree as ET 

import xml.etree.ElementTree as ET

tree = ET.parse('demo.xml')

#get root branch <item>
item = tree.getroot()

#loop through all <record> of <item>
for record in item.findall("record"):
email = record.find("email").text
country = record.find("country").text
print(f"Email: {email},-------->Country:{country}")
Email:,-------->Country:South Africa
Email:,-------->Country:Korea, South


That summarizes this tutorial on Python XML Parser. As should be obvious, Python gives an inbuild Standard XML module to peruse and parse XML records in Python. It by and large has 2 submodules that can parse an XML document:

  • ElementTree



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store