To write a Python dictionary to an XML file, you can use the built-in XML library xml.etree.ElementTree
. Here's an example code block:
main.py556 chars21 lines
In this example, dict_to_xml()
is a recursive function that converts a dictionary object to an ElementTree object. We pass the top-level dictionary object and the root element of the XML document to this function. For each key-value pair in the dictionary, we create an XML element with the key as the tag name and the value as the element text. If the value is another dictionary object, we recursively call dict_to_xml()
to add its elements to the current element.
After converting the dictionary to an XML document, we use the tostring()
method of the ElementTree object to generate an XML string, and write it to a file using the open()
function.
gistlibby LogSnag