How to convert XML into dictionary in Python?

Steve 33 Published: 09/12/2024

How to convert XML into dictionary in Python?

I'd be happy to help you with that!

Converting an XML file into a dictionary in Python can be achieved through the use of several libraries, including xml.etree.ElementTree and xml.dom.minidom.

Let's dive into it! We'll start by importing the necessary modules.

Firstly, we need to install the required packages if not already installed:

pip install xml.etree.ElementTree

Now that we have our libraries ready, let's write a Python program that converts an XML file into a dictionary. Let's assume that you have an XML file called "data.xml" with the following content:


John

25

Jane

30

Here's a Python code that reads this XML file and converts it into a dictionary:

import xml.etree.ElementTree as ET

def xml_to_dict(xml_file):

root = ET.parse(xml_file).getroot()

persons = {}

for person in root.findall('.//person'):

info = {'id': int(person.get('id')),

'name': person.find('name').text,

'age': int(person.find('age').text)}

persons[info['id']] = info

return persons

data_dict = xml_to_dict('data.xml')

for id, info in data_dict.items():

print(f"ID: {id}, Name: {info['name']}, Age: {info['age']}")

This script does the following:

It parses the XML file using ET.parse() and gets the root element of the document. It iterates through each <person> element in the XML file, extracting their IDs, names, and ages. It creates a dictionary for each person, with keys like 'id', 'name', and 'age'. Finally, it prints out all the people's information.

In this example, we are converting an XML into a Python dictionary that looks something like:

{

1: {'id': 1, 'name': 'John', 'age': 25},

2: {'id': 2, 'name': 'Jane', 'age': 30}

}

Note: Always remember that this is a very basic conversion. You might need to modify the script based on your specific requirements.

Hope this helps!

Xmltodict Python example

I'll respond in English only this time.

Xmltodict is a popular Python library used to convert XML (Extensible Markup Language) files into dictionary format, which is more human-readable and easier to process programmatically. Here's an example of how you can use xmltodict to parse an XML file:

First, install the xmltodict library using pip:

pip install xmltodict

Now, let's assume we have a simple XML file called person.xml with the following content:


John Doe

30

123 Main St

New York City

NY

10001

To parse this XML file using xmltodict, you can use the following Python code:

import xmltodict

with open('person.xml', 'r') as f:

xml_string = f.read()

xml_dict = xmltodict.parse(xml_string)

print(xml_dict)

This will output the following dictionary representation of the XML file:

{

"person": {

"name": "John Doe",

"age": 30,

"address": {

"street": "123 Main St",

"city": "New York City",

"state": "NY",

"zip": "10001"

}

}

}

As you can see, the XML file has been converted into a nested dictionary structure that's easy to work with. You can access specific values or traverse the hierarchy using standard Python dictionary syntax.

For example, to get the value of the name element, you would use:

print(xml_dict['person']['name'])  # Output: John Doe

Or, to get the entire address subtree as a separate dictionary, you can do:

address_dict = xml_dict['person']['address']

print(address_dict)

This will output:

{

"street": "123 Main St",

"city": "New York City",

"state": "NY",

"zip": "10001"

}

Xmltodict is a powerful tool for working with XML files in Python, and I hope this example has demonstrated its ease of use!