You can easily convert a Python Dict or a list of Dicts to a valid XML string. To do so, you need to first install the Python Package dicttoxml. Below is the PIP command install it.
pip install dicttoxmlCode language: Bash (bash)
Once you have installed the package using the above command, use the below function to convert any dictionary or list of dictionaries into an XML string.
from dicttoxml import dicttoxml from xml.dom.minidom import parseString def dict2xml(dict_or_list,root=True,custom_root='root',cdata=True,pretty_print=True,attr_type=False): xml = dicttoxml(dict_or_list, root=root, custom_root=custom_root, cdata=cdata, attr_type=attr_type) if pretty_print: dom = parseString(xml) return dom.toprettyxml() else: return xml.decode("utf-8")Code language: Python (python)
Pretty Print XML document
The above function by default will pretty print the resultant XML string, similar to how you pretty print JSON. That will make it more readable for human eyes and visually appealing if you want to further edit the XML document. You can disable pretty printing by setting the pretty_print argument to False.
Wrapping String values in CDATA of XML document
The cdata argument is True by default to wrap any string into CDATA tag in the output XML. You can set it to False, but that will mean that all XML specific characters like <,>, ” etc will be escaped into html entities like “<” “>”, “"” etc.
Complete XML document with a root element or an XML Snippet
By default the function will generate a complete XML document whose root is ‘root’. You can change the default root name to any value like ‘Items’ or ‘Products’ or whatever you want. If you want to generate an XML Snippet ie XML without any Root node so that you can insert that snippet into another XML document, then simply set root=False.
Type attribute for each Element to indicate value type
The attr_type which is False by default, will output additional type information for each element if set to True.