Created
August 28, 2020 01:50
-
-
Save phalt/b5cdf3d3d5e91879fd09429adb070244 to your computer and use it in GitHub Desktop.
Python dictionary to xml string
This file contains 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, tostring | |
def dict_to_xml(tag: str, d: dict) -> str: | |
""" | |
Converts a Python dictionary to an XML tree, and then returns | |
it as a string. | |
Works with recursively nested dictionaries! | |
"tag" is the name of the top-level XML tag. | |
""" | |
elem = Element(tag) | |
def _d_to_x(elem, d): | |
for key, val in d.items(): | |
child = Element(key) | |
if isinstance(val, dict): | |
elem.append(_d_to_x(Element(key), val)) | |
else: | |
child.text = str(val) | |
elem.append(child) | |
return elem | |
return tostring(_d_to_x(elem, d)).decode("utf-8") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this!
A small addition, if you like. To also use pretty formatting with an indent, and handle lists.
List elements will be added with the same root name, e,g, something like
will be converted to:
Here's the modification: