Created
April 17, 2014 19:39
-
-
Save bartek/11007051 to your computer and use it in GitHub Desktop.
Convert a list of dictionaries into an XML representation
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.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