Created
January 25, 2011 20:22
-
-
Save jacobian/795571 to your computer and use it in GitHub Desktop.
Convert an lxml.etree node tree into a dict.
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
| 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 else elem2dict(e) | |
| d[key] = value | |
| return d |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Round-trip not possible since the dict keys don't show if they were created from elements or attributes. To put a
@in front of the attribute-generated keys, changekey, result[key] = itemtokey, result[key] = '@' + item[0], item[1].