Python program to convert XML to Dictionary

Python program to convert XML to Dictionary

To convert an XML string to a Python dictionary, you can use the xmltodict library, which provides a simple way to achieve this conversion.

Here's a step-by-step guide:

1. Installation:

If you haven't already installed xmltodict, do so using pip:

pip install xmltodict 

2. Conversion:

Use the xmltodict.parse() function to convert an XML string to a Python dictionary:

import xmltodict def xml_to_dict(xml_str): return xmltodict.parse(xml_str) xml_data = """ <data> <person> <name>John</name> <age>30</age> <city>New York</city> </person> <person> <name>Mary</name> <age>25</age> <city>Los Angeles</city> </person> </data> """ dictionary_data = xml_to_dict(xml_data) print(dictionary_data) 

Output:

{ 'data': { 'person': [ { 'name': 'John', 'age': '30', 'city': 'New York' }, { 'name': 'Mary', 'age': '25', 'city': 'Los Angeles' } ] } } 

The xmltodict.parse() function provides a straightforward way to convert XML data to a dictionary format. If you need to convert back from a dictionary to XML, you can use the xmltodict.unparse() function.


More Tags

system-properties pdftk embedded-linux extends meta-tags webdriver-w3c-spec servletconfig tomcat7 bar-chart imagebackground

More Programming Guides

Other Guides

More Programming Examples