Converts a Python dictionary or other native data type into a valid XML string.
npx @tessl/cli install tessl/pypi-dicttoxml@1.7.0dicttoxml converts Python dictionaries and other native data types into valid XML strings. It supports arbitrary nesting of collections, handles various data type mappings to XML elements with optional type attributes, and can generate complete XML documents with proper headers and root elements or XML snippets for integration into larger documents.
pip install dicttoxmlimport dicttoxmlFor direct function access:
from dicttoxml import dicttoxmlimport dicttoxml
# Simple dictionary conversion
data = {
'name': 'John Doe',
'age': 30,
'city': 'New York',
'active': True
}
# Convert to XML with default settings
xml = dicttoxml.dicttoxml(data)
print(xml.decode('utf-8'))
# Output: <?xml version="1.0" encoding="UTF-8" ?><root><name type="str">John Doe</name><age type="int">30</age><city type="str">New York</city><active type="bool">true</active></root>
# Convert to XML snippet (no root element or declaration)
xml_snippet = dicttoxml.dicttoxml(data, root=False)
print(xml_snippet.decode('utf-8'))
# Output: <name type="str">John Doe</name><age type="int">30</age><city type="str">New York</city><active type="bool">true</active>
# Return as string instead of bytes
xml_string = dicttoxml.dicttoxml(data, return_bytes=False)
print(xml_string)dicttoxml supports these Python data types with automatic XML type mapping:
| Python Type | XML Type Attribute |
|---|---|
| int | int |
| float | float |
| bool | bool |
| str/unicode | str |
| None | null |
| datetime | str (ISO format) |
| decimal.Decimal | number |
| dict | dict |
| list/set/tuple | list |
Converts Python objects to XML with extensive customization options.
def dicttoxml(
obj,
root=True,
custom_root='root',
xml_declaration=True,
ids=False,
attr_type=True,
item_func=default_item_func,
cdata=False,
include_encoding=True,
encoding='UTF-8',
return_bytes=True
):
"""
Converts a python object into XML.
Parameters:
- obj: The Python object to convert (any supported data type)
- root (bool): Whether to wrap output in XML root element (default: True)
- custom_root (str): Custom root element name (default: 'root')
- xml_declaration (bool): Include XML declaration (default: True)
- ids (bool): Generate unique id attributes for elements (default: False)
- attr_type (bool): Include data type attributes (default: True)
- item_func (callable): Function to generate list item names (default: default_item_func)
- cdata (bool): Wrap string values in CDATA sections (default: False)
- include_encoding (bool): Include encoding in XML declaration (default: True)
- encoding (str): XML encoding type (default: 'UTF-8')
- return_bytes (bool): Return bytes vs string (default: True)
Returns:
bytes or str: XML representation of the input object
Raises:
TypeError: For unsupported data types
"""Controls debug logging for troubleshooting XML conversion issues.
def set_debug(debug=False, filename='dicttoxml.log'):
"""
Enable or disable debug logging.
Parameters:
- debug (bool): Enable debug mode (default: False)
- filename (str): Log filename (default: 'dicttoxml.log')
Returns:
None
"""Default function for generating list item element names, can be customized via item_func parameter.
def default_item_func(parent):
"""
Default function to generate element names for list items.
Parameters:
- parent (str): Parent element name
Returns:
str: Element name ('item')
"""import dicttoxml
data = {'message': 'Hello World'}
xml = dicttoxml.dicttoxml(data, custom_root='greeting', return_bytes=False)
print(xml)
# Output: <?xml version="1.0" encoding="UTF-8" ?><greeting><message type="str">Hello World</message></greeting>import dicttoxml
data = {'name': 'Alice', 'score': 95.5}
xml = dicttoxml.dicttoxml(data, attr_type=False, return_bytes=False)
print(xml)
# Output: <?xml version="1.0" encoding="UTF-8" ?><root><name>Alice</name><score>95.5</score></root>import dicttoxml
data = {'users': ['Alice', 'Bob', 'Charlie']}
xml = dicttoxml.dicttoxml(data, ids=True, return_bytes=False)
print(xml)
# Output includes unique id attributes like: <users id="root_123456" type="list"><item id="users_654321_1" type="str">Alice</item>...import dicttoxml
data = {'fruits': ['apple', 'banana', 'cherry']}
# Custom function to create singular item names
def singular_item(parent):
return parent[:-1] if parent.endswith('s') else 'item'
xml = dicttoxml.dicttoxml(data, item_func=singular_item, return_bytes=False)
print(xml)
# Output: <?xml version="1.0" encoding="UTF-8" ?><root><fruits type="list"><fruit type="str">apple</fruit><fruit type="str">banana</fruit><fruit type="str">cherry</fruit></fruits></root>import dicttoxml
data = {'html': '<div>Hello <b>World</b></div>'}
xml = dicttoxml.dicttoxml(data, cdata=True, return_bytes=False)
print(xml)
# Output: <?xml version="1.0" encoding="UTF-8" ?><root><html type="str"><![CDATA[<div>Hello <b>World</b></div>]]></html></root>import dicttoxml
from datetime import datetime
complex_data = {
'user': {
'id': 12345,
'name': 'John Doe',
'email': 'john@example.com',
'active': True,
'created': datetime(2023, 1, 15, 10, 30, 0),
'tags': ['developer', 'python', 'xml'],
'metadata': None,
'scores': [95.5, 87.2, 92.8]
}
}
xml = dicttoxml.dicttoxml(complex_data, return_bytes=False)
print(xml)import dicttoxml
data = {'message': 'Hello 世界'}
# Custom encoding
xml = dicttoxml.dicttoxml(data, encoding='ISO-8859-1', return_bytes=False)
# No encoding attribute
xml = dicttoxml.dicttoxml(data, include_encoding=False, return_bytes=False)
# No XML declaration at all
xml = dicttoxml.dicttoxml(data, xml_declaration=False, return_bytes=False)dicttoxml raises TypeError for unsupported data types:
import dicttoxml
try:
# This will raise TypeError
xml = dicttoxml.dicttoxml(object())
except TypeError as e:
print(f"Conversion error: {e}")__version__ = '1.7.16'
version = __version__ # Alias for __version__Access version information:
import dicttoxml
print(dicttoxml.__version__) # '1.7.16'
print(dicttoxml.version) # '1.7.16'