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.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay