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.
pip install dict2xmlVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to convert a nested Python dictionary into an XML string using the `dict2xml` function. It uses the `wrap` parameter to specify a root element and `indent` for readability.
Consider using a different library if XML attributes are a hard requirement, or structure your dictionary to represent attributes as child elements if possible. For example, `{ 'element': { 'attribute_key': 'attribute_value', 'content': 'text' } }` will result in nested elements, not an element with an attribute.If key order is important and you are not using an `OrderedDict`, you can provide a `data_sorter` to the `Converter` class. For example, `Converter(data_sorter=DataSorter.never()).build(data)` to prevent sorting keys, or `data_sorter=DataSorter.always()` to force sorting, even for `OrderedDict`.
Ensure your project is running on Python 3.6 or newer. If you need Python 2 compatibility, you must use an older version of the `dict2xml` library (e.g., < 1.7.0).
If an XML declaration is required, you must prepend it manually to the output string.
Install the library using pip: `pip install dict2xml`
After `import dict2xml`, call the function as `dict2xml.dict2xml(your_dict)` or use `from dict2xml import dict2xml` and call it as `dict2xml(your_dict)`. Alternatively, if using the class-based approach, import `Converter` and use `Converter().build(your_dict)`.
Ensure all values in your dictionary are of supported types (e.g., strings, numbers, booleans, lists, dictionaries, None, datetime objects) or convert unsupported types to strings before passing the dictionary to `dict2xml`.
Use a `collections.OrderedDict` for your input data and pass `data_sorter=DataSorter.never()` to `dict2xml.Converter().build()` or `data_sorter=False` if directly calling the `dict2xml` function to prevent key sorting, ensuring the original order is preserved.
```python
from dict2xml import dict2xml, Converter
from collections import OrderedDict
data = OrderedDict([('b', 2), ('a', 1)])
xml_string = dict2xml(data, data_sorter=False) # For the top-level function if it supports it
# Or using the Converter class explicitly:
converter = Converter()
xml_string = converter.build(data, data_sorter=Converter.DataSorter.never())
```No dependency data recorded yet.