or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/pypi-dicttoxml

Converts a Python dictionary or other native data type into a valid XML string.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/dicttoxml@1.7.x

To install, run

npx @tessl/cli install tessl/pypi-dicttoxml@1.7.0

index.mddocs/

dicttoxml

dicttoxml 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.

Package Information

  • Package Name: dicttoxml
  • Package Type: pypi
  • Language: Python
  • Installation: pip install dicttoxml
  • Python Requirements: Python 3.6+
  • License: GPL-2.0

Core Imports

import dicttoxml

For direct function access:

from dicttoxml import dicttoxml

Basic Usage

import 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)

Supported Data Types

dicttoxml supports these Python data types with automatic XML type mapping:

  • Primitives: int, float, bool, str, None, datetime objects, decimal.Decimal
  • Collections: dict, list, set, tuple, and any iterable or dict-like objects
  • Special handling: datetime objects → ISO format strings, None → empty XML elements

Type Mappings

Python TypeXML Type Attribute
intint
floatfloat
boolbool
str/unicodestr
Nonenull
datetimestr (ISO format)
decimal.Decimalnumber
dictdict
list/set/tuplelist

Capabilities

Main Conversion Function

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
    """

Debug Configuration

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
    """

Item Name Customization

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')
    """

Advanced Usage Examples

Custom Root Element

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>

Disabling Type Attributes

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>

Unique IDs for Elements

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>...

Custom List Item Names

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>

CDATA Sections

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>

Complex Nested Data

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)

Encoding Control

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)

Error Handling

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 Information

__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'