Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

Python program to convert XML to Dictionary

  • Last Updated : 14 Sep, 2021

In this article, we will discuss how to convert an XML to a dictionary using Python.

Modules Used

  • xmltodict: It is a Python module that makes working with XML feel like you are working with [JSON]. Run the following command in the terminal to install the module.

Syntax:

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

pip install xmltodict



  • pprint: The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a well-formatted and more readable way.

Approach

  • Import necessary module to working space.
  • Open the XML File in Read-only mode and read the contents using file.read() and store it in a variable.

Syntax:

with open('filename', 'r', encoding='utf-8') as file:
    my_xml = file.read()
  • Use xmltodict.parse() to parse the content from the variable and convert it into Dictionary.

Syntax : 

xmltodict.parse(xml_input, encoding=’utf-8′, expat=expat, process_namespaces=False, namespace_separator=’:’, **kwargs) 

Syntax : 

pprint.pprint(object, stream=None, indent=1, width=80, depth=None, *, compact=False, sort_dicts=True)

Example: Converting XML to dictionary

File Used:



Python3




# Import the required modules
import xmltodict
import pprint
  
# Open the file and read the contents
with open('example.xml', 'r', encoding='utf-8') as file:
    my_xml = file.read()
  
# Use xmltodict to parse and convert 
# the XML document
my_dict = xmltodict.parse(my_xml)
  
# Print the dictionary
pprint.pprint(my_dict, indent=2)

Output:

Example 2: Converting XML to dictionary

File Used:

Python3




# Import the required modules
import xmltodict
import pprint
  
# Open the file and read the contents
with open('example_2.xml', 'r', encoding='utf-8') as file:
    my_xml = file.read()
  
# Use xmltodict to parse and convert the 
# XML document
my_dict = xmltodict.parse(my_xml)
  
# Print the dictionary
pprint.pprint(my_dict, indent=2)

Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :