Last active
September 17, 2019 16:03
-
-
Save kjaquier/1e61ff4054577c54960d to your computer and use it in GitHub Desktop.
Serialize a Python dictionary to XML. Useful when working with both JSON and XML files. Doesn't work with object, lists, tuples or generators.
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
# -*- coding: Utf-8 -*- | |
import xml.etree.ElementTree as ET | |
def create_xml_tree(root, dict_tree): | |
# Node : recursively create tree nodes | |
if type(dict_tree) == dict: | |
for k, v in dict_tree.iteritems(): | |
create_xml_tree(ET.SubElement(root, k), v) | |
return root | |
# Leaf : just set the value of the current node | |
else: | |
root.text = str(dict_tree) | |
# | |
# TEST EXAMPLE | |
# | |
def prettify(elem): | |
"""Return a pretty-printed XML string for the Element. | |
Source : http://stackoverflow.com/questions/17402323/use-xml-etree-elementtree-to-write-out-nicely-formatted-xml-files | |
""" | |
from xml.dom import minidom | |
rough_string = ET.tostring(elem, 'utf-8') | |
reparsed = minidom.parseString(rough_string) | |
return reparsed.toprettyxml(indent="".join([' '] * 4)) | |
test = { | |
"Library" : { | |
"Book1": { | |
"Author": "Foo", | |
"Title": "How to foo", | |
"Year": 2014 | |
}, | |
"Book2": { | |
"Author": "Bar", | |
"Title": "How to bar", | |
"Year": 2012 | |
} | |
} | |
} | |
tree_root = create_xml_tree(ET.Element("root"), test) | |
# Not prettified | |
ET.ElementTree(tree_root).write("test.xml") | |
# Prettified | |
with open('test.xml', 'w') as output: | |
output.write(prettify(tree_root)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment