dict2xml
dict2xml is a small Python utility designed to convert a Python dictionary into an XML string. It is actively maintained, with frequent minor releases. The current version is 1.7.8.
Warnings
- gotcha The library does not support adding attributes directly to XML elements. Dictionary keys are treated as element names, and their values as element content.
- gotcha By default, `dict2xml` sorts dictionary keys alphabetically when converting them to XML elements, which can lead to unexpected ordering if not explicitly handled. `OrderedDict` keys are *not* sorted by default.
- breaking As of version 1.7.0, `dict2xml` officially dropped support for Python 2. It is now only supported for Python 3.6+ (though it may still work in 3.5).
- gotcha The library does not automatically include an XML declaration line (e.g., `<?xml version="1.0" encoding="UTF-8"?>`) in the generated XML string.
Install
-
pip install dict2xml
Imports
- dict2xml
from dict2xml import dict2xml
Quickstart
from dict2xml import dict2xml
data = {
'root_element': {
'item1': 123,
'item2': [
{'sub_item_a': 'hello'},
{'sub_item_b': 'world'}
],
'item3': {
'nested_value': 'example'
}
}
}
xml_string = dict2xml(data, wrap='root', indent=' ')
print(xml_string)