programmnig advise needed

Andrea Griffini agriff at tin.it
Tue Jun 7 18:02:48 EDT 2005


On 7 Jun 2005 12:14:45 -0700, mitsura at skynet.be wrote:

>I am writing a Python program that needs to read XML files and contruct
>a tree object from the XML file (using wxTree).

Supposing your XML file has a single top level node (so that it's a
legal XML file) then the following code should be able to read it...

#########
from elementtree import ElementTree as ET

class Node:
    def __init__(self, xmlnode):
        self.xmlnode = xmlnode
        self.children = []

def loadtree(f):
    root = ET.parse(f).getroot()
    nodes = {}
    for x in root:
        if x.tag.startswith("element"):
            nodes[x.tag] = Node(x)
    for x in root.findall("association"):
        name = x.find("Name").text
        parent = x.find("Parent").text
        nodes[parent].children.append(nodes.pop(name))
    assert len(nodes) == 1
    return nodes.popitem()[1]
##########

The idea is to create a node with an empty list of
logical children and then for every association
removing the child node from the global pool (a dict
indexed by node name) to place it in its parent.
I assumed that the nodes are in random order, but
that the associations are sorted bottom-up in
the tree. If this is not the case then you should
keep TWO dicts, removing from only one of them
the children when you process an association,
and looking up the parent in the *other* dict that
is not changed during processing of associations.
The dict from who you are removing the children
will allow you to detect logical errors in the file
(i.e. a node having two parents - you won't find
that node in the dict the second time - and absence
of a single root - you won't end up with a single
element in the dict after processing all
associations -).

HTH
Andrea



More information about the Python-list mailing list