You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

29 lines
887 B

4 years ago
  1. """Util functions used by Netdisco."""
  2. from collections import defaultdict
  3. # Taken from http://stackoverflow.com/a/10077069
  4. # pylint: disable=invalid-name
  5. def etree_to_dict(t):
  6. """Convert an ETree object to a dict."""
  7. # strip namespace
  8. tag_name = t.tag[t.tag.find("}")+1:]
  9. d = {tag_name: {} if t.attrib else None}
  10. children = list(t)
  11. if children:
  12. dd = defaultdict(list)
  13. for dc in map(etree_to_dict, children):
  14. for k, v in dc.items():
  15. dd[k].append(v)
  16. d = {tag_name: {k: v[0] if len(v) == 1 else v for k, v in dd.items()}}
  17. if t.attrib:
  18. d[tag_name].update(('@' + k, v) for k, v in t.attrib.items())
  19. if t.text:
  20. text = t.text.strip()
  21. if children or t.attrib:
  22. if text:
  23. d[tag_name]['#text'] = text
  24. else:
  25. d[tag_name] = text
  26. return d