MCPcopy Create free account
hub / github.com/ActiveState/code / nodeToDic

Function nodeToDic

recipes/Python/409899_xmlreader2/recipe-409899.py:32–79  ·  view source on GitHub ↗

nodeToDic() scans through the children of node and makes a dictionary from the content. three cases are differentiated: - if the node contains no other nodes, it is a text-node and {nodeName:text} is merged into the dictionary. - if there is more than one child with the same

(node)

Source from the content-addressed store, hash-verified

30
31
32def nodeToDic(node):
33 """
34 nodeToDic() scans through the children of node and makes a
35 dictionary from the content.
36 three cases are differentiated:
37 - if the node contains no other nodes, it is a text-node
38 and {nodeName:text} is merged into the dictionary.
39 - if there is more than one child with the same name
40 then these children will be appended to a list and this
41 list is merged to the dictionary in the form: {nodeName:list}.
42 - else, nodeToDic() will call itself recursively on
43 the nodes children (merging {nodeName:nodeToDic()} to
44 the dictionary).
45 """
46 dic = {}
47 multlist = {} # holds temporary lists where there are multiple children
48 for n in node.childNodes:
49 multiple = False
50 if n.nodeType != n.ELEMENT_NODE:
51 continue
52 # find out if there are multiple records
53 if len(node.getElementsByTagName(n.nodeName)) > 1:
54 multiple = True
55 # and set up the list to hold the values
56 if not multlist.has_key(n.nodeName):
57 multlist[n.nodeName] = []
58
59 try:
60 #text node
61 text = getTextFromNode(n)
62 except NotTextNodeError:
63 if multiple:
64 # append to our list
65 multlist[n.nodeName].append(nodeToDic(n))
66 dic.update({n.nodeName:multlist[n.nodeName]})
67 continue
68 else:
69 # 'normal' node
70 dic.update({n.nodeName:nodeToDic(n)})
71 continue
72
73 # text node
74 if multiple:
75 multlist[n.nodeName].append(text)
76 dic.update({n.nodeName:multlist[n.nodeName]})
77 else:
78 dic.update({n.nodeName:text})
79 return dic
80
81
82def readConfig(filename):

Callers 1

readConfigFunction · 0.70

Calls 4

getTextFromNodeFunction · 0.70
has_keyMethod · 0.45
appendMethod · 0.45
updateMethod · 0.45

Tested by

no test coverage detected