Skip to content

Instantly share code, notes, and snippets.

@marc-fez
Forked from jacobian/elem2dict.py
Last active May 23, 2017 13:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marc-fez/a3ea4b23ea59fd463770106a480f48f4 to your computer and use it in GitHub Desktop.
Save marc-fez/a3ea4b23ea59fd463770106a480f48f4 to your computer and use it in GitHub Desktop.
Convert an lxml.etree node tree into a dict.
def elem2dict(node):
"""
Convert an lxml.etree node tree into a dict.
"""
d = {}
for e in node.iterchildren():
key = e.tag.split('}')[1] if '}' in e.tag else e.tag
value = e.text if e.text.strip() else elem2dict(e)
d[key] = value
return d
@marc-fez
Copy link
Author

I kept finding white space returned where there should be deeper nodes, added the strip to the test for text existence.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment