2 import xml.etree.cElementTree as ElementTree
4 class XmlListConfig(list):
5 def __init__(self, aList):
9 if len(element) == 1 or element[0].tag != element[1].tag:
10 self.append(XmlDictConfig(element))
12 elif element[0].tag == element[1].tag:
13 self.append(XmlListConfig(element))
15 text = element.text.strip()
20 class XmlDictConfig(dict):
24 >>> tree = ElementTree.parse('your_file.xml')
25 >>> root = tree.getroot()
26 >>> xmldict = XmlDictConfig(root)
28 Or, if you want to use an XML string:
30 >>> root = ElementTree.XML(xml_string)
31 >>> xmldict = XmlDictConfig(root)
33 And then use xmldict for what it is... a dict.
35 def __init__(self, parent_element):
36 childrenNames = [child.tag for child in parent_element.getchildren()]
38 if parent_element.items(): #attributes
39 self.update(dict(parent_element.items()))
40 for element in parent_element:
42 # treat like dict - we assume that if the first two tags
43 # in a series are different, then they are all different.
44 if len(element) == 1 or element[0].tag != element[1].tag:
45 aDict = XmlDictConfig(element)
46 # treat like list - we assume that if the first two tags
47 # in a series are the same, then the rest are the same.
49 # here, we put the list in dictionary; the key is the
50 # tag name the list elements all share in common, and
51 # the value is the list itself
52 aDict = {element[0].tag: XmlListConfig(element)}
53 # if the tag has attributes, add those to the dict
55 aDict.update(dict(element.items()))
57 if childrenNames.count(element.tag) > 1:
59 currentValue = self[element.tag]
60 currentValue.append(aDict)
61 self.update({element.tag: currentValue})
62 except: #the first of its kind, an empty list must be created
63 self.update({element.tag: [aDict]}) #aDict is written in [], i.e. it will be a list
66 self.update({element.tag: aDict})
67 # this assumes that if you've got an attribute in a tag,
68 # you won't be having any text. This may or may not be a
69 # good idea -- time will tell. It works for the way we are
70 # currently doing XML configuration files...
72 self.update({element.tag: dict(element.items())})
73 # finally, if there are no child tags and no attributes, extract
76 self.update({element.tag: element.text})