class PropDict(dict):
"""Simple dict wrapper that allows element access as an attribute"""
def __getattr__(self, name):
return self[name]
def dictify(elem, collections=[]):
"""Convert from ElementTree.Element to a PropDict hierarchy. (Easily modifyable to return regular dicts.)
If you specify tag names in collections, all sub-elements will be sewn up into the parent collection:
<obj><lics><lic><id>1</id></lic><lic><id>2</id></lic><notlic>blah</notlic></lics></obj> becomes {lics:[{id:1},{id:2},'blah']}
"""
rval = PropDict()
for i in elem.getchildren():
if i.tag in collections:
rval[i.tag] = []
for j in i.getchildren():
rval[i.tag].append(dictify(j, collections))
elif rval.has_key(i.tag):
if not isinstance(rval[i.tag], list):
rval[i.tag] = [rval[i.tag]]
rval[i.tag].append(dictify(i, collections))
else:
children = i.getchildren()
if len(children):
rval[i.tag] = dictify(i, collections)
else:
rval[i.tag] = i.text
if not rval.has_key('text') and elem.text and elem.text.strip():
rval['text'] = elem.text.strip()
return rval
Convert ElemntTree to a dictionary, huzzah.