Skip to content

Instantly share code, notes, and snippets.

@bartek
Created April 17, 2014 19:39
Show Gist options
  • Save bartek/11007051 to your computer and use it in GitHub Desktop.
Save bartek/11007051 to your computer and use it in GitHub Desktop.
Convert a list of dictionaries into an XML representation
from xml.etree.ElementTree import Element, SubElement
def dict_to_xml(data, root_name='events'):
# a list of dictionaries, converted into xml.
root = Element(root_name)
def _make_xml(i_root, data_dict):
for field, val in data_dict.iteritems():
if isinstance(val, dict):
i_data = SubElement(i_root, field)
_make_xml(i_data, val)
else:
SubElement(i_root, field).text = str(val)
for data_dict in data:
item_root = SubElement(root, root_name[:-1])
_make_xml(item_root, data_dict)
return root
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment