is it possible to build an XML string from a Python structure (e.g. nested lists, dictionaries, etc.) or it is a non-sense question?
Is there any standard tool?
Thanks
is it possible to build an XML string from a Python structure (e.g. nested lists, dictionaries, etc.) or it is a non-sense question?
Is there any standard tool?
Thanks
If you need some custom format, you can use xml.etree.ElementTree to programatically generate such a format. For example:
from xml.etree import ElementTree
def dict2xml(d, parent=None):
if parent is None:
parent = ElementTree.Element('xml')
for key, value in d.items():
if isinstance(value, str):
element = ElementTree.SubElement(parent, key)
element.text = value
elif isinstance(value, dict):
element = ElementTree.SubElement(parent, key)
dict2xml(value, element)
elif isinstance(value, list):
for text in value:
element = ElementTree.SubElement(parent, key)
element.text = str(text)
else:
raise TypeError('Unexpected value type: {0}'
.format(type(value)))
return parent
d = {'a': 'a contents',
'b': {'c': 'c contents',
'd': 'd contents',
},
'e': range(3),
}
print ElementTree.tostring(dict2xml(d))
Generates the following output:
<xml><a>a contents</a><b><c>c contents</c><d>d contents</d></b><e>0</e><e>1</e><e>2</e></xml>