Created
March 10, 2016 22:11
-
-
Save b1tninja/ef4366e7c7c463235f65 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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