9 functions to convert an XML file into a python dict, back and forth
11 __author__ =
"Sebastien Binet <binet@cern.ch>"
14 from xml.etree
import ElementTree
16 from xml.sax.saxutils
import escape
as _xml_escape
17 from xml.sax.saxutils
import unescape
as _xml_unescape
30 dict.__init__(self, initdict)
33 return self.__getitem__(item)
36 self.__setitem__(item, value)
53 return dict.__str__(self)
57 if isinstance(x, dict):
58 return XmlDictObject ((k, XmlDictObject.wrap(v))
59 for (k, v)
in x.iteritems())
60 elif isinstance(x, list):
61 return [XmlDictObject.wrap(v)
for v
in x]
67 if isinstance(x, dict):
68 return dict ((k, XmlDictObject._unwrap(v))
69 for (k, v)
in x.iteritems())
70 elif isinstance(x, list):
71 return [XmlDictObject._unwrap(v)
for v
in x]
76 return XmlDictObject._unwrap(self)
79 assert type(dictitem)
is not type(list)
81 if isinstance(dictitem, dict):
82 for (tag, child)
in dictitem.iteritems():
83 if isinstance(child, str):
84 child = _xml_escape(child)
85 if str(tag) ==
'_text':
86 parent.text =
str(child)
88 for listchild
in child:
89 elem = ElementTree.Element(tag)
91 _dict2xml_recurse (elem, listchild)
93 elem = ElementTree.Element(tag)
95 _dict2xml_recurse (elem, child)
97 parent.text =
str(dictitem)
100 """convert a python dictionary into an XML tree"""
101 roottag = xmldict.keys()[0]
102 root = ElementTree.Element(roottag)
103 _dict2xml_recurse (root, xmldict[roottag])
107 nodedict = dictclass()
109 if len(node.items()) > 0:
111 nodedict.update(dict((k, _xml_unescape(v)
if isinstance(v, str)
else v)
112 for k,v
in node.items()))
116 newitem = _xml2dict_recurse (child, dictclass)
117 if isinstance(newitem, str):
118 newitem = _xml_unescape(newitem)
119 if child.tag
in nodedict:
121 if isinstance(nodedict[child.tag], list):
123 nodedict[child.tag].
append(newitem)
126 nodedict[child.tag] = [nodedict[child.tag], newitem]
129 nodedict[child.tag] = newitem
131 if node.text
is None:
134 text = node.text.strip()
136 if len(nodedict) > 0:
140 nodedict[
'_text'] = text
143 if node.text: nodedict = node.text.strip()
149 """convert an xml tree into a python dictionary
151 return dictclass({root.tag: _xml2dict_recurse (root, dictclass)})