~jstys-z/helioviewer.org/client5

« back to all changes in this revision

Viewing changes to install/hvpull/validation/__init__.py

  • Committer: Keith Hughitt
  • Date: 2012-04-23 16:02:25 UTC
  • mto: This revision was merged to the branch mainline in revision 732.
  • Revision ID: keith.hughitt@nasa.gov-20120423160225-xzoh82ejf37c8yr7
Incorporated HVPull code

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
 
 
2
 
 
3
#
 
4
# Converting XML to a Dictionary
 
5
# Author: Christoph Dietze
 
6
# URL   : http://code.activestate.com/recipes/116539/
 
7
#
 
8
class NotTextNodeError(Exception):
 
9
    pass
 
10
 
 
11
def xml_to_dict(xmlstring):
 
12
    """Converts an XML string to a Python dictionary"""
 
13
    return node_to_dict(parseString(xmlstring))
 
14
 
 
15
def node_to_dict(node):
 
16
    """
 
17
    node_to_dict() scans through the children of node and makes a dictionary 
 
18
    from the content.
 
19
    
 
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).
 
28
    """
 
29
    dic = {} 
 
30
    for n in node.childNodes:
 
31
        if n.nodeType != n.ELEMENT_NODE:
 
32
            continue
 
33
        if n.getAttribute("multiple") == "true":
 
34
            # node with multiple children: put them in a list
 
35
            l = []
 
36
            for c in n.childNodes:
 
37
                if c.nodeType != n.ELEMENT_NODE:
 
38
                    continue
 
39
                l.append(node_to_dict(c))
 
40
                dic.update({n.nodeName: l})
 
41
            continue
 
42
            
 
43
        try:
 
44
            text = get_node_text(n)
 
45
        except NotTextNodeError:
 
46
            # 'normal' node
 
47
            dic.update({n.nodeName: node_to_dict(n)})
 
48
            continue
 
49
    
 
50
        # text node
 
51
        dic.update({n.nodeName: text})
 
52
        continue
 
53
    return dic
 
54
 
 
55
def get_node_text(node):
 
56
    """
 
57
    scans through all children of node and gathers the text. if node has 
 
58
    non-text child-nodes, then NotTextNodeError is raised.
 
59
    """
 
60
    t = ""
 
61
    for n in node.childNodes:
 
62
        if n.nodeType == n.TEXT_NODE:
 
63
            t += n.nodeValue
 
64
        else:
 
65
            raise NotTextNodeError
 
66
    return t
 
 
b'\\ No newline at end of file'