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.
pip install dicttoxmlVerified import paths — ran on the pinned version, not inferred.
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.
Pass `attr_type=False` to the `dicttoxml` function: `dicttoxml(my_dict, attr_type=False)`.
To change the root element, use `custom_root='my_custom_tag'`. To generate an XML snippet without the root or declaration, pass `root=False` to `dicttoxml()`.
Sanitize dictionary keys to be valid XML element names before conversion, or be aware of `dicttoxml`'s automatic handling.
Disable debugging output by calling `dicttoxml.set_debug(False)` or configure Python's `logging` module to suppress `dicttoxml`'s output.
Ensure that all values in your dictionary are of supported types (e.g., int, float, str, bool, datetime, None, list, dict, set, tuple). If you have a custom or unsupported object, convert it to a string or another compatible type before passing it to `dicttoxml`.
Modify your import statement from `import dicttoxml` to `from dicttoxml import dicttoxml`. Additionally, check your project directory and Python path for any files or folders named `dicttoxml.py` or `dicttoxml` that might be conflicting with the installed library.
Decode the byte string using `.decode('utf-8')` to convert it into a standard UTF-8 string for display or further processing. Example: `xml_bytes = dicttoxml(my_dict); xml_string = xml_bytes.decode('utf-8')`.