converting XML to hash/dict/CustomTreeCtrl

Nobody nobody at
Wed Feb 3 16:50:56 CET 2010

On Wed, 03 Feb 2010 08:07:50 +1100, Astan Chee wrote:

> Sorry for being vague but here my question about converting an xml into 
> a dict. I found some examples online but none gives the dict/result I 
> want.

> Which is kinda wrong. I expect the dict to have the "Space usage 
> summary", but it doesn't (duplicate?). What am I doing wrong here?
> I am attempting to keep the attribute value of an XML as key (if it 
> doesn't have a value, then just the tag name will do) and associate it 
> with the text value of that tag/attribute value as well as reflecting 
> the hierarchy structure of the XML in the dict. Does this make sense?
> Anyway, the python script above is just the first step or an example for me.

The code you're using expects the XML to follow a particular format, and
yours doesn't.

You might want to start with a fairly direct translation, e.g.:

def xmldict(e):
    d = {}
    d['tag'] = e.tag
    children = map(xmldict, e)
    if children:
	d['children'] = children
    text = e.text.strip()
    if text:
	d['text'] = text
    return d

tree = ElementTree.parse('test.xml')
root = tree.getroot()
d = xmldict(root)

then refine this as needed.

More information about the Python-list mailing list