summaryrefslogtreecommitdiff
path: root/netdisco/util.py
blob: 65475b4582c4b417898c96cce2fa60d21b9a9302 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
"""Util functions used by Netdisco."""
from collections import defaultdict


# Taken from http://stackoverflow.com/a/10077069
# pylint: disable=invalid-name
def etree_to_dict(t):
    """Convert an ETree object to a dict."""
    # strip namespace
    tag_name = t.tag[t.tag.find("}")+1:]

    d = {tag_name: {} if t.attrib else None}
    children = list(t)
    if children:
        dd = defaultdict(list)
        for dc in map(etree_to_dict, children):
            for k, v in dc.items():
                dd[k].append(v)
        d = {tag_name: {k: v[0] if len(v) == 1 else v for k, v in dd.items()}}
    if t.attrib:
        d[tag_name].update(('@' + k, v) for k, v in t.attrib.items())
    if t.text:
        text = t.text.strip()
        if children or t.attrib:
            if text:
                d[tag_name]['#text'] = text
        else:
            d[tag_name] = text
    return d