Turning a Dictionary into XML in Python

Turning a Dictionary into XML in Python

Turning a dictionary into XML in Python can be achieved using several libraries. One of the simplest methods is using the xml.etree.ElementTree module that comes with the standard library.

Here's a basic example to convert a dictionary into XML using this module:

import xml.etree.ElementTree as ET def dict_to_xml(tag, dictionary): """ Convert a dictionary to an XML Element. """ elem = ET.Element(tag) for key, val in dictionary.items(): child = ET.Element(key) child.text = str(val) elem.append(child) return elem # Sample dictionary data = { 'name': 'John', 'age': 30, 'city': 'New York' } # Convert dictionary to XML root = dict_to_xml('person', data) # Create a string representation of the XML xml_str = ET.tostring(root, encoding='utf-8', method='xml').decode('utf-8') print(xml_str) 

Output:

<person><name>John</name><age>30</age><city>New York</city></person> 

If your dictionary is more complex (e.g., contains nested dictionaries), you would need to modify the dict_to_xml function to handle recursion.

For more complex needs or if you want more control over the resulting XML, you might consider using third-party libraries such as xmltodict or lxml.


More Tags

android-edittext npm-scripts jwk ngx-cookie-service shortest-path oledbdataadapter azure-cli2 array-column numeric-input seed

More Programming Guides

Other Guides

More Programming Examples