Skip to content

Instantly share code, notes, and snippets.

@pluma
Last active December 20, 2015 16:49
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 pluma/6164350 to your computer and use it in GitHub Desktop.
Save pluma/6164350 to your computer and use it in GitHub Desktop.
from lxml import etree
def node_from_dict(tag, data=None):
node = etree.Element(tag)
if isinstance(data, dict):
for key, value in data.items():
if isinstance(value, list):
for v in value:
node.append(node_from_dict(key, v))
else:
node.append(node_from_dict(key, value))
else:
node.text = data
return node
def dict_from_nodes(nodes):
data = {}
for node in nodes:
children = node.getchildren()
key = node.tag
value = dict_from_nodes(children) if children else node.text
if key not in data:
data[key] = value
elif not isinstance(data[key], list):
data[key] = [data[key], value]
else:
data[key].append(value)
return data
@pluma
Copy link
Author

pluma commented Aug 6, 2013

Example usage:

>>> xml = "<?xml version='1.0' encoding='ASCII'?>\n<response><bleh>TRUE</bleh><foo>bar</foo><foo>qux</foo></response>"
>>> node = etree.fromstring(xml)
>>> data = dict_from_nodes(node.getchildren())
>>> data['foo']
['bar', 'qux']
>>> node = node_from_dict('response', data)
>>> xml == etree.tostring(node, xml_declaration=True)
True

License: CC0 http://creativecommons.org/publicdomain/zero/1.0/

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