Converts a Python dictionary or other native data type into a valid XML string.
npx @tessl/cli install tessl/pypi-dicttoxml@1.7.00
# dicttoxml
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: dicttoxml
7
- **Package Type**: pypi
8
- **Language**: Python
9
- **Installation**: `pip install dicttoxml`
10
- **Python Requirements**: Python 3.6+
11
- **License**: GPL-2.0
12
13
## Core Imports
14
15
```python
16
import dicttoxml
17
```
18
19
For direct function access:
20
21
```python
22
from dicttoxml import dicttoxml
23
```
24
25
## Basic Usage
26
27
```python
28
import dicttoxml
29
30
# Simple dictionary conversion
31
data = {
32
'name': 'John Doe',
33
'age': 30,
34
'city': 'New York',
35
'active': True
36
}
37
38
# Convert to XML with default settings
39
xml = dicttoxml.dicttoxml(data)
40
print(xml.decode('utf-8'))
41
# 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>
42
43
# Convert to XML snippet (no root element or declaration)
44
xml_snippet = dicttoxml.dicttoxml(data, root=False)
45
print(xml_snippet.decode('utf-8'))
46
# Output: <name type="str">John Doe</name><age type="int">30</age><city type="str">New York</city><active type="bool">true</active>
47
48
# Return as string instead of bytes
49
xml_string = dicttoxml.dicttoxml(data, return_bytes=False)
50
print(xml_string)
51
```
52
53
## Supported Data Types
54
55
dicttoxml supports these Python data types with automatic XML type mapping:
56
57
- **Primitives**: int, float, bool, str, None, datetime objects, decimal.Decimal
58
- **Collections**: dict, list, set, tuple, and any iterable or dict-like objects
59
- **Special handling**: datetime objects → ISO format strings, None → empty XML elements
60
61
### Type Mappings
62
63
| Python Type | XML Type Attribute |
64
|-------------|-------------------|
65
| int | int |
66
| float | float |
67
| bool | bool |
68
| str/unicode | str |
69
| None | null |
70
| datetime | str (ISO format) |
71
| decimal.Decimal | number |
72
| dict | dict |
73
| list/set/tuple | list |
74
75
## Capabilities
76
77
### Main Conversion Function
78
79
Converts Python objects to XML with extensive customization options.
80
81
```python { .api }
82
def dicttoxml(
83
obj,
84
root=True,
85
custom_root='root',
86
xml_declaration=True,
87
ids=False,
88
attr_type=True,
89
item_func=default_item_func,
90
cdata=False,
91
include_encoding=True,
92
encoding='UTF-8',
93
return_bytes=True
94
):
95
"""
96
Converts a python object into XML.
97
98
Parameters:
99
- obj: The Python object to convert (any supported data type)
100
- root (bool): Whether to wrap output in XML root element (default: True)
101
- custom_root (str): Custom root element name (default: 'root')
102
- xml_declaration (bool): Include XML declaration (default: True)
103
- ids (bool): Generate unique id attributes for elements (default: False)
104
- attr_type (bool): Include data type attributes (default: True)
105
- item_func (callable): Function to generate list item names (default: default_item_func)
106
- cdata (bool): Wrap string values in CDATA sections (default: False)
107
- include_encoding (bool): Include encoding in XML declaration (default: True)
108
- encoding (str): XML encoding type (default: 'UTF-8')
109
- return_bytes (bool): Return bytes vs string (default: True)
110
111
Returns:
112
bytes or str: XML representation of the input object
113
114
Raises:
115
TypeError: For unsupported data types
116
"""
117
```
118
119
### Debug Configuration
120
121
Controls debug logging for troubleshooting XML conversion issues.
122
123
```python { .api }
124
def set_debug(debug=False, filename='dicttoxml.log'):
125
"""
126
Enable or disable debug logging.
127
128
Parameters:
129
- debug (bool): Enable debug mode (default: False)
130
- filename (str): Log filename (default: 'dicttoxml.log')
131
132
Returns:
133
None
134
"""
135
```
136
137
### Item Name Customization
138
139
Default function for generating list item element names, can be customized via item_func parameter.
140
141
```python { .api }
142
def default_item_func(parent):
143
"""
144
Default function to generate element names for list items.
145
146
Parameters:
147
- parent (str): Parent element name
148
149
Returns:
150
str: Element name ('item')
151
"""
152
```
153
154
## Advanced Usage Examples
155
156
### Custom Root Element
157
158
```python
159
import dicttoxml
160
161
data = {'message': 'Hello World'}
162
xml = dicttoxml.dicttoxml(data, custom_root='greeting', return_bytes=False)
163
print(xml)
164
# Output: <?xml version="1.0" encoding="UTF-8" ?><greeting><message type="str">Hello World</message></greeting>
165
```
166
167
### Disabling Type Attributes
168
169
```python
170
import dicttoxml
171
172
data = {'name': 'Alice', 'score': 95.5}
173
xml = dicttoxml.dicttoxml(data, attr_type=False, return_bytes=False)
174
print(xml)
175
# Output: <?xml version="1.0" encoding="UTF-8" ?><root><name>Alice</name><score>95.5</score></root>
176
```
177
178
### Unique IDs for Elements
179
180
```python
181
import dicttoxml
182
183
data = {'users': ['Alice', 'Bob', 'Charlie']}
184
xml = dicttoxml.dicttoxml(data, ids=True, return_bytes=False)
185
print(xml)
186
# Output includes unique id attributes like: <users id="root_123456" type="list"><item id="users_654321_1" type="str">Alice</item>...
187
```
188
189
### Custom List Item Names
190
191
```python
192
import dicttoxml
193
194
data = {'fruits': ['apple', 'banana', 'cherry']}
195
196
# Custom function to create singular item names
197
def singular_item(parent):
198
return parent[:-1] if parent.endswith('s') else 'item'
199
200
xml = dicttoxml.dicttoxml(data, item_func=singular_item, return_bytes=False)
201
print(xml)
202
# 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>
203
```
204
205
### CDATA Sections
206
207
```python
208
import dicttoxml
209
210
data = {'html': '<div>Hello <b>World</b></div>'}
211
xml = dicttoxml.dicttoxml(data, cdata=True, return_bytes=False)
212
print(xml)
213
# Output: <?xml version="1.0" encoding="UTF-8" ?><root><html type="str"><![CDATA[<div>Hello <b>World</b></div>]]></html></root>
214
```
215
216
### Complex Nested Data
217
218
```python
219
import dicttoxml
220
from datetime import datetime
221
222
complex_data = {
223
'user': {
224
'id': 12345,
225
'name': 'John Doe',
226
'email': 'john@example.com',
227
'active': True,
228
'created': datetime(2023, 1, 15, 10, 30, 0),
229
'tags': ['developer', 'python', 'xml'],
230
'metadata': None,
231
'scores': [95.5, 87.2, 92.8]
232
}
233
}
234
235
xml = dicttoxml.dicttoxml(complex_data, return_bytes=False)
236
print(xml)
237
```
238
239
### Encoding Control
240
241
```python
242
import dicttoxml
243
244
data = {'message': 'Hello 世界'}
245
246
# Custom encoding
247
xml = dicttoxml.dicttoxml(data, encoding='ISO-8859-1', return_bytes=False)
248
249
# No encoding attribute
250
xml = dicttoxml.dicttoxml(data, include_encoding=False, return_bytes=False)
251
252
# No XML declaration at all
253
xml = dicttoxml.dicttoxml(data, xml_declaration=False, return_bytes=False)
254
```
255
256
## Error Handling
257
258
dicttoxml raises `TypeError` for unsupported data types:
259
260
```python
261
import dicttoxml
262
263
try:
264
# This will raise TypeError
265
xml = dicttoxml.dicttoxml(object())
266
except TypeError as e:
267
print(f"Conversion error: {e}")
268
```
269
270
## Version Information
271
272
```python { .api }
273
__version__ = '1.7.16'
274
version = __version__ # Alias for __version__
275
```
276
277
Access version information:
278
279
```python
280
import dicttoxml
281
print(dicttoxml.__version__) # '1.7.16'
282
print(dicttoxml.version) # '1.7.16'
283
```