Skip to content

Instantly share code, notes, and snippets.

@b1tninja
Created March 10, 2016 22:11
Show Gist options
  • Save b1tninja/ef4366e7c7c463235f65 to your computer and use it in GitHub Desktop.
Save b1tninja/ef4366e7c7c463235f65 to your computer and use it in GitHub Desktop.
from xml.etree import ElementTree
import string
def parse(xml):
root = ElementTree.fromstring(xml)
return root.tag, tree_to_dict(root)
def tree_to_dict(element, parents=None):
if parents is None:
parents = []
else:
parents = list(parents)
parents.append(element.tag)
prefix = '_'.join(parents[1:])
# sanitize attribute keys
d = dict([('{}_{}'.format(prefix, ''.join([c if c in string.ascii_letters else '_' for c in k])), v) for k,v in element.attrib.items()])
text = element.text.strip()
if text:
d[prefix] = text
for child in element:
d.update(tree_to_dict(child, parents))
return d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment