DEV Community

Hodunov
Hodunov

Posted on

Recursive XML parsing using ElementTree module in Python

Alt Text
Working with files in python is not a difficult task.

Suppose you have the task of converting an xml file coming to you into a python dictionary. And then do some manipulation with it at your discretion.

How do you handle this task with as little code as possible? We are lazy, right?
By using recursion, of course.
Let's see how to do it without using any external libraries. Python has a nice ElementTree XML API



import xml.etree.ElementTree as ET


def xml_to_dict_recursive(root):
    """
    Recursively walk through the root and turn it into a dict.
    :param root: <class 'xml.etree.ElementTree.Element'>
    :return: dict
    """
    for children in root.iter():
        if len(children) == 0:
            return {root.tag: root.text.strip()}
        else:
            return {root.tag: list(map(xml_to_dict_recursive, children))}


def convert_xml_file_to_dict(file):
    """Process the kml file and return the dictionary."""
    tree = ET.parse(file)
    root = tree.getroot()
    return xml_to_dict_recursive(root)


with open('note.xml') as file:
    xml_dict = convert_xml_file_to_dict(file)


Enter fullscreen mode Exit fullscreen mode

Easier than leaving office on Friday!
Python is a wonderful language for working with data.

Top comments (0)