🔍 Code Extractor

function unparse

Maturity: 60

Converts a Python dictionary into an XML document string, serving as the reverse operation of XML parsing. Supports customizable formatting, encoding, and XML generation options.

File:
/tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/xmltodict.py
Lines:
476 - 516
Complexity:
moderate

Purpose

This function serializes Python dictionaries into well-formed XML documents. It's designed to work as the inverse of an XML parser, converting structured dictionary data back into XML format. The function handles XML attributes (keys prefixed with '@'), character data (keys equal to '#text'), and supports both full document generation and XML fragments. It's useful for generating XML configuration files, API responses, or any scenario requiring XML output from Python data structures.

Source Code

def unparse(input_dict, output=None, encoding='utf-8', full_document=True,
            short_empty_elements=False,
            **kwargs):
    """Emit an XML document for the given `input_dict` (reverse of `parse`).

    The resulting XML document is returned as a string, but if `output` (a
    file-like object) is specified, it is written there instead.

    Dictionary keys prefixed with `attr_prefix` (default=`'@'`) are interpreted
    as XML node attributes, whereas keys equal to `cdata_key`
    (default=`'#text'`) are treated as character data.

    The `pretty` parameter (default=`False`) enables pretty-printing. In this
    mode, lines are terminated with `'\n'` and indented with `'\t'`, but this
    can be customized with the `newl` and `indent` parameters.

    """
    if full_document and len(input_dict) != 1:
        raise ValueError('Document must have exactly one root.')
    must_return = False
    if output is None:
        output = StringIO()
        must_return = True
    if short_empty_elements:
        content_handler = XMLGenerator(output, encoding, True)
    else:
        content_handler = XMLGenerator(output, encoding)
    if full_document:
        content_handler.startDocument()
    for key, value in input_dict.items():
        _emit(key, value, content_handler, full_document=full_document,
              **kwargs)
    if full_document:
        content_handler.endDocument()
    if must_return:
        value = output.getvalue()
        try:  # pragma no cover
            value = value.decode(encoding)
        except AttributeError:  # pragma no cover
            pass
        return value

Parameters

Name Type Default Kind
input_dict - - positional_or_keyword
output - None positional_or_keyword
encoding - 'utf-8' positional_or_keyword
full_document - True positional_or_keyword
short_empty_elements - False positional_or_keyword
**kwargs - - var_keyword

Parameter Details

input_dict: Dictionary containing the data to be converted to XML. Keys represent XML element names, and values represent element content. Special keys like '@attribute_name' represent XML attributes, and '#text' represents character data. If full_document=True, must contain exactly one root element.

output: Optional file-like object where the XML output will be written. If None (default), the function returns the XML as a string. If provided, XML is written to this object and nothing is returned.

encoding: String specifying the character encoding for the XML document. Default is 'utf-8'. Common values include 'utf-8', 'ascii', 'iso-8859-1', etc.

full_document: Boolean indicating whether to generate a complete XML document with XML declaration. If True (default), includes startDocument() and endDocument() calls and enforces single root element. If False, generates XML fragment without declaration.

short_empty_elements: Boolean controlling how empty XML elements are rendered. If True, uses self-closing tags like <element/>. If False (default), uses separate opening and closing tags like <element></element>.

**kwargs: Additional keyword arguments passed to the internal _emit function. May include 'attr_prefix' (default '@'), 'cdata_key' (default '#text'), 'pretty' (default False), 'newl' (newline character), and 'indent' (indentation string) for formatting control.

Return Value

Returns a string containing the generated XML document if 'output' parameter is None. The string is encoded according to the 'encoding' parameter and decoded back to a Python string. If 'output' parameter is provided (file-like object), returns None as the XML is written directly to the output object.

Dependencies

  • xml.sax.saxutils
  • io

Required Imports

from xml.sax.saxutils import XMLGenerator
from io import StringIO

Usage Example

from xml.sax.saxutils import XMLGenerator
from io import StringIO

# Basic usage - convert dictionary to XML string
input_data = {
    'root': {
        '@version': '1.0',
        'item': [
            {'@id': '1', '#text': 'First item'},
            {'@id': '2', '#text': 'Second item'}
        ],
        'metadata': {
            'author': 'John Doe',
            'date': '2024-01-01'
        }
    }
}

xml_string = unparse(input_data)
print(xml_string)
# Output: <?xml version="1.0" encoding="utf-8"?><root version="1.0"><item id="1">First item</item><item id="2">Second item</item><metadata><author>John Doe</author><date>2024-01-01</date></metadata></root>

# Write to file
with open('output.xml', 'w', encoding='utf-8') as f:
    unparse(input_data, output=f)

# Generate XML fragment without document declaration
fragment_data = {'element': 'content'}
xml_fragment = unparse(fragment_data, full_document=False)

# Use short empty elements
empty_data = {'root': {'empty_element': None}}
xml_short = unparse(empty_data, short_empty_elements=True)

Best Practices

  • Ensure input_dict has exactly one root key when full_document=True to avoid ValueError
  • Use '@' prefix for dictionary keys that should become XML attributes (e.g., '@id', '@class')
  • Use '#text' as the key for character data within elements that also have attributes
  • Specify encoding parameter to match your target system's requirements, especially for non-ASCII characters
  • When writing to files, use the output parameter instead of capturing return value for better memory efficiency with large XML documents
  • Set full_document=False when generating XML fragments to be embedded in larger documents
  • Use short_empty_elements=True for more compact XML when dealing with many empty elements
  • Pass pretty=True in kwargs for human-readable formatted output during development/debugging
  • The function depends on an internal _emit function that must be available in the same module

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function parse 66.1% similar

    Parses XML input (string, file-like object, or generator) and converts it into a Python dictionary representation with configurable options for attributes, namespaces, comments, and streaming.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/xmltodict.py
  • function _emit 65.1% similar

    Recursively converts a dictionary structure into XML SAX events, emitting them through a content handler for XML generation.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/xmltodict.py
  • class _DictSAXHandler 59.5% similar

    A SAX (Simple API for XML) event handler that converts XML documents into Python dictionaries, with extensive configuration options for handling attributes, namespaces, CDATA, and structure.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/xmltodict.py
  • function print_json 45.1% similar

    A utility function that prints a Python dictionary as formatted JSON with 2-space indentation to standard output.

    From: /tf/active/vicechatdev/test_acl_functions.py
  • function _process_namespace 40.7% similar

    Processes XML namespace prefixes in element/attribute names by resolving them against a namespace dictionary and reconstructing the full qualified name.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/xmltodict.py
← Back to Browse