XML Element to Nested Dictionary Conversion

  • Share this:

Code introduction


This function takes an XML element as input and parses it into a nested dictionary. Each child element becomes a key in the dictionary, with its text content as the value.


Technology Stack : Lxml

Code Type : Python Function

Code Difficulty : Intermediate


                
                    
import lxml.etree as etree

def parse_element_to_dict(element):
    """
    Converts an XML element to a dictionary.
    """
    result = {}
    for child in element:
        child_data = {}
        for subchild in child:
            child_data[subchild.tag] = subchild.text
        result[child.tag] = child_data
    return result

# JSON representation                
              
Tags: