dicttoxml
dicttoxml is a Python library that converts a Python dictionary or other native data types (like lists, sets, tuples, integers, strings, booleans, and datetime objects) into a valid XML string. It supports arbitrary nesting for collections and offers options to control XML declaration, root element, and type attributes. The current version is 1.7.16, actively maintained to support Python 3.6 and forward versions.
Warnings
- gotcha By default, `dicttoxml` includes a `type` attribute for each element (e.g., `<name type="str">`). This can lead to verbose XML if not desired.
- gotcha The converted XML is wrapped in a `<root>` element by default, and includes an XML declaration (`<?xml version="1.0" encoding="UTF-8" ?>`).
- gotcha Element names that are not valid XML (e.g., contain spaces or special characters) are automatically converted. Spaces become underscores, and severely invalid names become `<key name="original-invalid-name">`.
- gotcha The library enables verbose logging by default, which can clutter console output or log files with INFO-level messages for every conversion step.
Install
-
pip install dicttoxml
Imports
- dicttoxml
from dicttoxml import dicttoxml
- dicttoxml module
import dicttoxml
Quickstart
from dicttoxml import dicttoxml
import xml.dom.minidom
my_dict = {
'name': 'Alice',
'age': 30,
'is_student': False,
'courses': [
{'title': 'Math', 'credits': 3},
{'title': 'Science', 'credits': 4}
],
'address': {'street': '123 Main St', 'city': 'Anytown'}
}
# Convert dictionary to XML with default settings
xml_bytes = dicttoxml(my_dict)
# Pretty print the XML (optional)
dom = xml.dom.minidom.parseString(xml_bytes)
pretty_xml_string = dom.toprettyxml()
print(pretty_xml_string)