9 functions to convert an XML file into a python dict, back and forth
11 __author__ =
"Sebastien Binet <binet@cern.ch>"
26 xml_site_package = os.path.join(os.path.dirname(os.__file__),
'xml')
27 m = imp.find_module(
'etree', [xml_site_package])
29 etree = imp.load_module(
'xml.etree', *m)
34 from xml.etree
import ElementTree
36 from xml.sax.saxutils
import escape
as _xml_escape
37 from xml.sax.saxutils
import unescape
as _xml_unescape
50 dict.__init__(self, initdict)
53 return self.__getitem__(item)
56 self.__setitem__(item, value)
73 return dict.__str__(self)
77 if isinstance(x, dict):
78 return XmlDictObject ((k, XmlDictObject.wrap(v))
79 for (k, v)
in x.iteritems())
80 elif isinstance(x, list):
81 return [XmlDictObject.wrap(v)
for v
in x]
87 if isinstance(x, dict):
88 return dict ((k, XmlDictObject._unwrap(v))
89 for (k, v)
in x.iteritems())
90 elif isinstance(x, list):
91 return [XmlDictObject._unwrap(v)
for v
in x]
96 return XmlDictObject._unwrap(self)
99 assert type(dictitem)
is not type(list)
101 if isinstance(dictitem, dict):
102 for (tag, child)
in dictitem.iteritems():
103 if isinstance(child, str):
104 child = _xml_escape(child)
105 if str(tag) ==
'_text':
106 parent.text =
str(child)
108 for listchild
in child:
109 elem = ElementTree.Element(tag)
111 _dict2xml_recurse (elem, listchild)
113 elem = ElementTree.Element(tag)
115 _dict2xml_recurse (elem, child)
117 parent.text =
str(dictitem)
120 """convert a python dictionary into an XML tree"""
121 roottag = xmldict.keys()[0]
122 root = ElementTree.Element(roottag)
123 _dict2xml_recurse (root, xmldict[roottag])
127 nodedict = dictclass()
129 if len(node.items()) > 0:
131 nodedict.update(dict((k, _xml_unescape(v)
if isinstance(v, str)
else v)
132 for k,v
in node.items()))
136 newitem = _xml2dict_recurse (child, dictclass)
137 if isinstance(newitem, str):
138 newitem = _xml_unescape(newitem)
139 if child.tag
in nodedict:
141 if isinstance(nodedict[child.tag], list):
143 nodedict[child.tag].
append(newitem)
146 nodedict[child.tag] = [nodedict[child.tag], newitem]
149 nodedict[child.tag] = newitem
151 if node.text
is None:
154 text = node.text.strip()
156 if len(nodedict) > 0:
160 nodedict[
'_text'] = text
163 if node.text: nodedict = node.text.strip()
169 """convert an xml tree into a python dictionary
171 return dictclass({root.tag: _xml2dict_recurse (root, dictclass)})