converting XML to hash/dict/CustomTreeCtrl

Astan Chee astan.chee at
Tue Feb 2 22:07:50 CET 2010

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. The xml looks like this:
    <stats name="position1" description="Calculation statistics"
    <stats name="time" description="Timing summary" kind="section">
        <string name="timersNote" description="Note:">This is the note
on calculation times</string>
        <stats name="timers" kind="timers">

        <timer name="totaltime" description="Total time">
        <timer name="partialTimer" description="Gravitational Displacement">
        <stats name="subTimers" description="All non-phased time" 
            <timer name="subATimer" description="Phase time A">

            <timer name="subBTimer" description="Phase time B">
            <timer name="spaceMem" description="Space memory">
        <timer name="endTime" description="End">
    <stats name="space" description="Space usage summary" kind="section">
        <stats name="systemSpace" description="System Space">
        <memory name="heapSpace" description="Total Space">

        <memory name="spaceResidentSize" description="Space resident size">
        <int name="pageMem">1</int>

        <int name="memReclaims">1943498</int>
        <int name="memSwaps">0</int>
        <stats name="subsystems" kind="memstats">
        <memory name="geoSpace" description="Geo-Space">
        <memory name="gridSpace" description="Grid-Space">
        <memory name="spaceMem" description="Space memory">
                <memory name="endTime" description="End">
            <memory name="subsystemSpace" description="Subsystem space

using this script (taken from
from xml.etree import cElementTree as ElementTree

class XmlListConfig(list):
    def __init__(self, aList):
        for element in aList:
            if element:
                # treat like dict
                if len(element) == 1 or element[0].tag != element[1].tag:
                # treat like list
                elif element[0].tag == element[1].tag:
            elif element.text:
                text = element.text.strip()
                if text:

class XmlDictConfig(dict):
    Example usage:

    >>> tree = ElementTree.parse('your_file.xml')
    >>> root = tree.getroot()
    >>> xmldict = XmlDictConfig(root)

    Or, if you want to use an XML string:

    >>> root = ElementTree.XML(xml_string)
    >>> xmldict = XmlDictConfig(root)

    And then use xmldict for what it is... a dict.
    def __init__(self, parent_element):
        if parent_element.items():
        for element in parent_element:
            if element:
                # treat like dict - we assume that if the first two tags
                # in a series are different, then they are all different.
                if len(element) == 1 or element[0].tag != element[1].tag:
                    aDict = XmlDictConfig(element)
                # treat like list - we assume that if the first two tags
                # in a series are the same, then the rest are the same.
                    # here, we put the list in dictionary; the key is the
                    # tag name the list elements all share in common, and
                    # the value is the list itself
                    aDict = {element[0].tag: XmlListConfig(element)}
                # if the tag has attributes, add those to the dict
                if element.items():
                self.update({element.tag: aDict})
            # this assumes that if you've got an attribute in a tag,
            # you won't be having any text. This may or may not be a
            # good idea -- time will tell. It works for the way we are
            # currently doing XML configuration files...
            elif element.items():
                self.update({element.tag: dict(element.items())})
            # finally, if there are no child tags and no attributes, extract
            # the text
                self.update({element.tag: element.text})
tree = ElementTree.parse('test.xml')
root = tree.getroot()

xmldict = XmlDictConfig(root)
print xmldict

Which I get this dict:
{'stats': {'kind': 'position', 'stats': [{'kind': 'section', 'stats': 
{'kind': 'timers', 'name': 'timers', 'timer': [{'system': '65.119100', 
'user': '2531.972081', 'elapsed': '609.081574', 'name': 'totaltime', 
'description': 'Total time'}, {'elapsed': '1772.011230', 'name': 
'partialTimer', 'description': 'Gravitational Displacement'}, 
[{'elapsed': '72.418861', 'name': 'subATimer', 'description': 'Phase 
time A'}, {'elapsed': '28.285192', 'name': 'subBTimer', 'description': 
'Phase time B'}, {'elapsed': '0.000', 'name': 'spaceMem', 'description': 
'Space memory'}], {'elapsed': '607.432373', 'name': 'endTime', 
'description': 'End'}]}, 'name': 'time', 'string': {'name': 
'timersNote', 'description': 'Note:'}, 'description': 'Timing summary'}, 
[[{'current': '4833280000', 'peak': '4833280000', 'name': 'heapSpace', 
'description': 'Total Space'}, {'current': '4182777856', 'peak': 
'4182777856', 'name': 'spaceResidentSize', 'description': 'Space 
resident size'}, '1', '1943498', '0'], [{'current': '411307840', 'peak': 
'1640100156', 'name': 'geoSpace', 'description': 'Geo-Space'}, 
{'current': '1406752', 'peak': '709596712', 'name': 'gridSpace', 
'description': 'Grid-Space'}, {'current': '0', 'peak': '737720720', 
'name': 'spaceMem', 'description': 'Space memory'}, {'peak': 
'607.432373', 'name': 'endTime', 'description': 'End'}], {'current': 
'2054715622', 'peak': '5164184694', 'name': 'subsystemSpace', 
'description': 'Subsystem space  total'}]], 'name': 'position1', 
'description': 'Calculation statistics'}}

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.
Cheers and thanks again

More information about the Python-list mailing list