dicttoxml

1.7.16 · active · verified Sat Apr 11

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

Install

Imports

Quickstart

This quickstart demonstrates how to convert a Python dictionary into an XML string using `dicttoxml` and then pretty-prints the output using `xml.dom.minidom` for readability.

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)

view raw JSON →