Skip to content

Instantly share code, notes, and snippets.

@mforets
Created October 20, 2016 10:05
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 mforets/7ba47a60f6cc81e43456e622bae79fdf to your computer and use it in GitHub Desktop.
Save mforets/7ba47a60f6cc81e43456e622bae79fdf to your computer and use it in GitHub Desktop.
Convert Python dictionaries into XML
r"""Convert Python dictionaries into XML.
AUTHORS:
- Marcelo Forets
EXAMPLES:
python: d = list()
python: d.append({'id':1, 'text':'foo'})
python: d.append({'id':2, 'text':'boo'})
python: print convert(d)
<?xml version="1.0" ?>
<root_element>
<element num="1">
<text>foo</text>
<id>1</id>
</element>
<element num="2">
<text>boo</text>
<id>2</id>
</element>
</root_element>
REFERENCES:
- The code for pretty XML printing is from: https://pymotw.com/2/xml/etree/ElementTree/create.html
"""
# *****************************************************************************
# Copyright (C) 2016 Marcelo Forets <mforets@nonlinearnotes.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# any later version.
# http://www.gnu.org/licenses/
# *****************************************************************************
from xml.etree import ElementTree
from xml.etree.ElementTree import Element, SubElement
from xml.dom import minidom
def prettify(elem):
r"""Return a pretty-printed XML string for the Element.
"""
rough_string = ElementTree.tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent=" ")
def convert(source_dict):
r""" Convert a list of dictionaries (or a list of dictionaries of dictionaries) into an XML file.
"""
root = Element('root_element')
for i, element in enumerate(source_dict, 1):
new_element = SubElement(root, 'element', num=str(i))
for key in element:
new_child = SubElement(new_element, key)
if type(element[key]) == dict:
for sub_key in element[key]:
new_sub_child = SubElement(new_child, sub_key)
new_sub_child.text = str(element[key][sub_key])
else:
new_child.text = str(element[key])
return prettify(root)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment