Converts a Python dictionary or other native data type into a valid XML string.
Details
Supports item (int, float, long, decimal.Decimal, bool, str, unicode, datetime, none and other number-like objects) and collection (list, set, tuple and dict, as well as iterable and dict-like objects) data types, with arbitrary nesting for the collections. Items with a datetime type are converted to ISO format strings. Items with a None type become empty XML elements.
The root object passed into the dicttoxml method can be any of the supported data types.
To satisfy XML syntax, the method prepends an <?xml version="1.0" encoding="UTF-8" ?> element and wraps the output in a <root> ... </root> element. However, this can be disabled to create XML snippets. Alternately, a custom root element can be specified by passing in the optional custom_root=foobar argument.
For lists of items, if each item is also a collection data type (lists, dict), the elements of that item are wrapped in a generic <item> ... </item> element.
Each element includes an optional type attribute with the data type. By default, the type attribute it included but it can be excluded by passing an optional attr_type=False argument when calling the dicttoxml method.
Note: datetime data types are converted into ISO format strings, and unicode and datetime data types get a str attribute.
Python -> XML
integer int
long long
float float
Decimal number
string str
unicode str
datetime str
None null
boolean bool
list list
set list
tuple list
dict dict
Elements with an unsupported data type raise a TypeError exception.
If an element name is invalid XML, it is rendered with the name "key" and the invalid name is included as a name attribute. E.g. { "^.{0,256}$": "foo" } would be rendered <key name="^.{0,256}$">foo</key>. An exception is element names with spaces, which are converted to underscores.
This module should work in Python 3.6+. You might be able to get it to work in Python 2.x but that is no longer supported.
Alternately, you can download the tarballed installer - dicttoxml-[VERSION].tar.gz - for this package from the dist directory on github and uncompress it. Then, from a terminal or command window, navigate into the unzipped folder and type the command:
python setup.py install
That should be all you need to do.
Basic Usage
Once installed, import the library into your script and convert a dict into xml by running the dicttoxml function:
>>> import dicttoxml
>>> xml = dicttoxml.dicttoxml(some_dict)
Alternately, you can import the dicttoxml() function from the library.
>>> from dicttoxml import dicttoxml
>>> xml = dicttoxml(some_dict)
That's it!
JSON to XML
Let's say you want to fetch a JSON object from a URL and convert it into XML. Here's how you can do that:
With the optional root argument set to False, the method converts the dict into XML without including an <?xml> prolog or a <root> element to enclose all the other elements.
Custom Root
By default, dicttoxml wraps all the elements in a <root> ... </root> element. Starting in version 1.5, you can change the name of the root element to something else by passing an optional custom_root=some_custom_root argument to the dicttoxml method.
As you can see, the name of the root element has changed to some_custom_root.
Omit XML Declaration
Perhaps you want your outputted XML to have a root but no XML declaration. Starting with version 1.7.15, can call dicttoxml with the optional xml_declaration argument set to False:
As you can see, the XML declaration has been omitted.
Disable Type Attributes
By default, dicttoxml includes a type attribute for each element. Starting in version 1.4, you can turn this off by passing an optional attr_type=False argument to the dicttoxml method.
As you can see, the only difference is that the type attributes are now absent.
Change or Suppress XML Encoding Attribute
By default, dicttoxml renders the XML element with an encoding="UTF-8" attribute. Starting in version 1.7.6, you can change the encoding by using the optional encoding argument to the dicttoxml method. For example, to render an XML file with encoding "ISO-8859-1", you would call:
>>> xml = dicttoxml.dicttoxml(obj, encoding="ISO-8859-1")
Or if you prefer, you can suppress the encoding attribute altogether by setting the optional include_encoding argument to False:
>>> xml = dicttoxml.dicttoxml(obj, include_encoding=False)
Again, by default, the include_encoding argument is set to True and the encoding argument is set to UTF-8.
Unique ID Attributes
Starting in version 1.1, you can set an optional ids parameter so that dicttoxml gives each element a unique id attribute.
With the ids flag on, the function generates a unique randomly-generated ID for each element based on the parent element in the form parent_unique. For list items, the id is in the form parent_unique_index.
As always, this remains compatible with arbitrary nesting of objects and types.
Define Custom Item Names
Starting in version 1.7, if you don't want item elements in a list to be called 'item', you can specify the element name using a function that takes the parent element name (i.e. the list name) as an argument.
The benefit of taking the parent element name as an argument is that you can write the function to do something with it. Let's say you have an object with some lists of specific items:
If you do not set cdata to True, the default value is False and values are not wrapped.
Return a String
By default, dicttoxml outputs the generated XML as a bytes object:
>>> xml = dicttoxml.dicttoxml(obj)
>>> type(xml).__name__
'bytes'
Starting in version 1.7.14, when you call the dicttoxml function, you can set an optional return_bytes argument to False to return a str object instead:
>>> xml = dicttoxml.dicttoxml(obj, return_bytes=False)
>>> type(xml).__name__
'str'
But by default, return_bytes is set to True.
Pretty-Printing
As they say, Python comes with batteries included. You can easily syntax-check and pretty-print your XML using Python's xml.dom.minidom module.
This makes the XML easier to read. If it is not well-formed, the xml parser will raise an exception.
Debugging
You can enable debugging informationby calling the set_debug() method:
>>> import dicttoxml
>>> dicttoxml.set_debug(debug=True)
Debug mode is on. Events are logged at: dicttoxml.log
>>> xml = dicttoxml.dicttoxml(some_dict)
By default, debugging information is logged to dicttoxml.log, but you can change this:
>>> dicttoxml.set_debug(debug=True, filename='/path/to/some_other_filename.log')
Debug mode is on. Events are logged at: some_other_filename.log
To turn debug mode off, just call set_debug with an argument of False:
First of all, sorry for such a log delay between releases! I have not been a responsible steward of this project and I aim to change that from now on. This is the first in a series of updates I will be pushing over the next couple of months to get caught up on the backlog of issues and pull requests.
Added ability to customize list and dict item names via a function argument passed into the dicttoxml() function. Customizeable item name function takes the item's parent element as an argument. Big thanks to viktor-zireael on Github, via pull request #40.
Updated code style to more closely follow PEP8.
Version 1.6.6
Release Date: 2015-04-09
Changes:
PyPi does not want to upload version 1.6.5. It's returning an Upload failed (500): Internal Server Error message when I try to upload the code. I'm incrementing the version by one and reinstalling it to see if that fixes the issue.
Version 1.6.5
Release Date: 2015-04-09
Changes:
Fixed issue #37, elements with boolean values were getting a "number" type attribute. The issue was that isinstance(True, numbers.Number) returns True. I modified the get_xml_type() function to test for boolean before testing for numbers.Number. Thanks to badsequel for identifying and reporting the issue.
Version 1.6.4
Release Date: 2015-03-11
Changes:
Fixed issue #36, logging was throwing an UnicodeDecodeError on non-ASCII characters in dictionary values. Thanks to beef9999 for identifying and reporting the issue.
Version 1.6.3
Release Date: 2015-03-05
Changes:
Updated README.markdown to reflect changes made in v. 1.6.2.
Version 1.6.2
Release Date: 2015-03-05
Changes:
Fixed issue #35, dicttoxml fails to identify a decimal.Decimal as a number. This is done by replacing type(val).__name__ in ('int', 'long') with the more generic isinstance(val, number.Number). Thanks to jmagnusson for finding and fixing the error.
Version 1.6.1
Release Date: 2015-03-05
Changes:
Merged pull request #34, fix misleading TypeError in convert_dict(). Thanks to jmagnusson for finding and fixing the error.
Version 1.6.0
Release Date: 2015-02-23
Changes:
Fixed issue #32, duplication in test for list-like data types.
Version 1.5.9
Release Date: 2015-02-23
Changes:
Merged pull request #33 to replace invocations of logging with LOG. Thanks to mfriedenhagen for identifying the issue with the logger, and to seyhuns for supplying a pull request that could be merged automatically.
Updated MANIFEST.in and setup.py so the licence and readme are properly included in the distribution.
Version 1.3.6
Release Date: 2014-04-21
Changes:
Added MANIFEST.in to include the LICENCE.txt and README.markdown files in the distribution, as per issue #15.
Version 1.3.5
Release Date: 2014-04-14
Changes:
dicttoxml() accepts [None] as a parameter and returns a valid XML object, as per issue #13.
Version 1.3.4
Release Date: 2014-04-14
Changes:
dicttoxml() now accepts None as a parameter and returns a valid XML object, as per issue #13.
Version 1.3.3
Release Date: 2014-04-14
Changes:
Automatically converts spaces in key names to underscores, as per issue #12.
Version 1.3.2
Release Date: 2014-04-14
Changes:
Added convert_none() function to convert a null value into XML
Added key_is_valid_xml() function to test if a key is valid XML
Updated convert_kv(), convert_bool() and convert_none() functions to test whether the key is a valid XML name and, if it is not, to render it as <key name="{invalidname}">value</key>. This addresses issue 10.
Version 1.3.1
Release Date: 2013-07-12
Changes:
Updated README to note support for dict-like and iterable objects.
Version 1.3
Release Date: 2013-07-12
Changes:
changed test for dict type from type(x)=dict to isinstance(x,dict) to include dict-like subclases derived from dict, as per issue 9.
Added test for isinstance(x,collections.Iterable) to test for list, set, tuple to accommodate iterable objects, as per issue 9.
Version 1.2
Release Date: 2013-07-11
Changes:
Fixed typo in convert_list() exception raise as per issue 8.
Version 1.1.2
Release Date: 2013-05-06
Changes:
Renamed github repo from dict2xml to dicttoxml to match PyPI name.
Version 1.1.1
Release Date: 2013-05-06
Changes:
Fixed README.markdown
Version 1.1
Release Date: 2013-05-06
Changes:
Added an optional ids argument to give each element a unique, randomly generated id attribute.
All elements now inlcude a type attribute.
Updated readme with more examples and Python 3 compatible syntax.