Package deefuzzer :: Package deefuzzer :: Package tools :: Module xmltodict
[hide private]
[frames] | no frames]

Source Code for Module deefuzzer.deefuzzer.tools.xmltodict

 1  #!/usr/bin/env python 
 2   
 3  # Easily import simple XML data to Python dictionary 
 4  # http://www.gmta.info/publications/parsing-simple-xml-structure-to-a-python-dictionary 
 5   
 6  import xml.dom.minidom 
 7   
8 -def haschilds(dom):
9 # Checks whether an element has any childs 10 # containing real tags opposed to just text. 11 for childnode in dom.childNodes: 12 if childnode.nodeName != "#text" and \ 13 childnode.nodeName != "#cdata-section": 14 return True 15 return False
16
17 -def indexchilds(dom, enc):
18 childsdict = dict() 19 for childnode in dom.childNodes: 20 name = childnode.nodeName.encode(enc) 21 if name == "#text" or name == "#cdata-section": 22 # ignore whitespaces 23 continue 24 if haschilds(childnode): 25 v = indexchilds(childnode, enc) 26 else: 27 v = childnode.childNodes[0].nodeValue.encode(enc) 28 if name in childsdict: 29 if isinstance(childsdict[name], dict): 30 # there is multiple instances of this node - convert to list 31 childsdict[name] = [childsdict[name]] 32 childsdict[name].append(v) 33 else: 34 childsdict[name] = v 35 return childsdict
36
37 -def xmltodict(data, enc=None):
38 dom = xml.dom.minidom.parseString(data.strip()) 39 return indexchilds(dom, enc)
40