Python Tip: Convert XML Tree To A Dictionary
home // page // Python Tip: Convert XML Tree To A Dictionary

Python Tip: Convert XML Tree To A Dictionary

I was doing a simple XML integration with SOAP service today and it really struck me that a lot of the data manipulation would be easier if the data was a dictionary. In addition, the XML returned was guaranteed to be fairly small and have only a handful of schemas – so a full-blown SAX parser wasn’t really necessary as there was no risk of overflowing memory with the raw XML data. So I decided to write a simple recursive algorithm to do the conversion. I’m posting it here in the hopes it saves someone else a bit of time in the future:

 

This seems to “Do The Right Thing” — for example, if you give it the following test data:

You get the following dictionary out:

 

NOTE: For the CS geeks out there, this does an post-order traversal of the XML tree. Also, this does not handle attributes.

EDIT: There’s a pretty concise answer on StackOverflow, but the results it returns are¬†different from what I wanted.