4
# Converting XML to a Dictionary
5
# Author: Christoph Dietze
6
# URL : http://code.activestate.com/recipes/116539/
8
class NotTextNodeError(Exception):
11
def xml_to_dict(xmlstring):
12
"""Converts an XML string to a Python dictionary"""
13
return node_to_dict(parseString(xmlstring))
15
def node_to_dict(node):
17
node_to_dict() scans through the children of node and makes a dictionary
20
Three cases are differentiated:
21
1. If the node contains no other nodes, it is a text-node and
22
{nodeName: text} is merged into the dictionary.
23
2. If the node has the attribute "method" set to "true", then it's children
24
will be appended to a list and this list is merged to the dictionary in
25
the form: {nodeName:list}.
26
3. Else, node_to_dict() will call itself recursively on the nodes children
27
(merging {nodeName: node_to_dict()} to the dictionary).
30
for n in node.childNodes:
31
if n.nodeType != n.ELEMENT_NODE:
33
if n.getAttribute("multiple") == "true":
34
# node with multiple children: put them in a list
36
for c in n.childNodes:
37
if c.nodeType != n.ELEMENT_NODE:
39
l.append(node_to_dict(c))
40
dic.update({n.nodeName: l})
44
text = get_node_text(n)
45
except NotTextNodeError:
47
dic.update({n.nodeName: node_to_dict(n)})
51
dic.update({n.nodeName: text})
55
def get_node_text(node):
57
scans through all children of node and gathers the text. if node has
58
non-text child-nodes, then NotTextNodeError is raised.
61
for n in node.childNodes:
62
if n.nodeType == n.TEXT_NODE:
65
raise NotTextNodeError
b'\\ No newline at end of file'