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:
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)
- Use pprint(pretty print) to print the dictionary in well-formatted and readable way.
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: