Converting XML to Dictionary in Python using lxml

There are many solutions on StackOverflow for converting XML to Python dictionary, but none of them generate the result I am looking for. I have the following XML:

<?xml version="1.0" encoding="UTF-8"?>
<status xmlns:mystatus="http://localhost/mystatus">
<section1
    mystatus:field1="data1"
    mystatus:field2="data2" />
<section2
    mystatus:lineA="outputA"
    mystatus:lineB="outputB" />
</status>

      

lxml has an elegant simple solution for converting XML to dictionary:

def recursive_dict(element):
 return element.tag, dict(map(recursive_dict, element)) or element.text

      

Unfortunately I am getting:

('status', {'section2': None, 'section1': None})

      

instead:

('status', {'section2': 
                       {'field1':'data1','field2':'data2'}, 
            'section1': 
                       {'lineA':'outputA','lineB':'outputB'}
            })

      

I cannot figure out how to get the desired result without significantly complicating the recursive_dict () function.

I am not tied to lxml and I am also fine with another dictionary organization if it gives me all the information in the xml. Thank!

+3


source to share


1 answer


I personally like it xmltodict

from here . On linux, you can install it with pip install xmltodict

.

Note that this actually creates objects OrderedDict

. Usage example:



import xmltodict as xd

with open('test.xml','r') as f:
    d = xd.parse(f)

      

+9


source







All Articles