Skip to content

Instantly share code, notes, and snippets.

@dedenhabibi
Last active February 5, 2020 12:27
Show Gist options
  • Save dedenhabibi/36d0cc9c733be6bfcfd6c710e0350755 to your computer and use it in GitHub Desktop.
Save dedenhabibi/36d0cc9c733be6bfcfd6c710e0350755 to your computer and use it in GitHub Desktop.
Function to convert dict/list into XML, with support attribute
from xml.etree.ElementTree import Element, tostring
def xml_to_str(the_xml):
return tostring(the_xml)
def list_to_xml(each_tag, the_list):
elements = []
for item in the_list:
element = Element(each_tag)
if type(item) is list:
child_elements = list_to_xml(each_tag, item)
for e in child_elements:
elements.append(e)
continue
if type(item) is dict:
elements.append(dict_to_xml(each_tag, item))
continue
else:
element.text = str(item)
elements.append(element)
return elements
def dict_to_xml(wrap_tag, the_dict):
element = Element(wrap_tag)
for key, val in the_dict.items():
if key.startswith('@'):
element.set(key[1:], str(val))
continue
if type(val) is dict:
element.append(dict_to_xml(key, val))
continue
if type(val) is list:
elements = list_to_xml(key, val)
for e in elements:
element.append(e)
continue
else:
child = Element(key)
child.text = str(val)
element.append(child)
return element
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment