quandyfactory / dicttoxml

Simple library to convert a Python dictionary or other native data type into a valid XML string.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Bug: dict value with unsupported type fails silently

quandyfactory opened this issue · comments

If you pass in a dict and one of the values is an unsupported type (e.g. a datetime object), the code doesn't raise an exception - it just passes silently over the value without adding it to the XML output. Here's an example that produces the issue:

>>> import dict2xml
>>> import datetime
>>> now = datetime.datetime.today()
>>> mydict = { 'name': 'Joe Blow', 'time': now }
>>> xml = dict2xml.dict2xml(mydict)
>>> print xml
<?xml version="1.0" encoding="UTF-8" ?><root><name type="str">Joe Blow</name></root>
>>> # the 'time' key and its datetime value just silently disappeared

I propose the following fix:

  • Raise an exception in convert_dict() and convert_list() if one of the elements is an unsupported type (currently, only convert() raises an exception).
  • Include an optional parameter that will automatically convert datetimes into UTC strings in the XML output.
  • Include an optional parameter that will automatically convert other unsupported types into their string representations.

One easy way to handle datetimes is to check an object for hasattr(obj, 'isoformat') and return obj.isoformat() if it does.

Fixed in release 0.5. Now supports datetime (converts to ISO format string) and set (converts to list) data types, and raises a TypeError exception on an unsupported data type.