Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

data type for each element to be made optional in the resulting xml #17

Merged
merged 5 commits into from
Jun 3, 2014
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
117 changes: 78 additions & 39 deletions dicttoxml.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,24 +72,24 @@ def key_is_valid_xml(key):
except Exception: #minidom does not implement exceptions well
return False

def convert(obj, ids, parent='root'):
def convert(obj, ids, parent='root',attr_type=True):
"""Routes the elements of an object to the right function to convert them based on their data type"""
logging.info('Inside convert(). obj type is: %s' % (type(obj).__name__))
if type(obj) in (int, float, str, unicode):
return convert_kv('item', obj)
return convert_kv('item', obj,attr_type)
if hasattr(obj, 'isoformat'):
return convert_kv('item', obj.isoformat())
return convert_kv('item', obj.isoformat(),attr_type)
if type(obj) == bool:
return convert_bool('item', obj)
return convert_bool('item', obj,attr_type)
if obj == None:
return convert_none('item', '')
return convert_none('item', '',attr_type)
if isinstance(obj, dict):
return convert_dict(obj, ids, parent)
return convert_dict(obj, ids, parent,attr_type)
if type(obj) in (list, set, tuple) or isinstance(obj, collections.Iterable):
return convert_list(obj, ids, parent)
return convert_list(obj, ids, parent,attr_type)
raise TypeError('Unsupported data type: %s (%s)' % (obj, type(obj).__name__))

def convert_dict(obj, ids, parent):
def convert_dict(obj, ids, parent,attr_type=True):
"""Converts a dict into an XML string."""
logging.info('Inside convert_dict(): obj type is: %s' % (type(obj).__name__))
output = []
Expand All @@ -107,26 +107,36 @@ def convert_dict(obj, ids, parent):
attr = {} if ids == False else {'id': '%s' % (this_id) }

if type(v) in (int, float, str, unicode):
addline(convert_kv(k, v, attr))
addline(convert_kv(k, v, attr,attr_type))
elif hasattr(v, 'isoformat'): # datetime
addline(convert_kv(k, v.isoformat(), attr))
addline(convert_kv(k, v.isoformat(), attr,attr_type))
elif type(v) == bool:
addline(convert_bool(k, v, attr))
addline(convert_bool(k, v, attr,attr_type))
elif isinstance(v, dict):
addline('<%s type="dict"%s>%s</%s>' % (
k, make_attrstring(attr), convert_dict(v, ids, k), k)
)
if not attr_type:
addline('<%s %s>%s</%s>' % (
k, make_attrstring(attr), convert_dict(v, ids, k,attr_type), k)
)
else:
addline('<%s type="dict"%s>%s</%s>' % (
k, make_attrstring(attr), convert_dict(v, ids, k,attr_type), k)
)
elif type(v) in (list, set, tuple) or isinstance(v, collections.Iterable):
addline('<%s type="list"%s>%s</%s>' % (
k, make_attrstring(attr), convert_list(v, ids, k), k)
)
if not attr_type:
addline('<%s %s>%s</%s>' % (
k, make_attrstring(attr), convert_list(v, ids, k,attr_type), k)
)
else:
addline('<%s type="list"%s>%s</%s>' % (
k, make_attrstring(attr), convert_list(v, ids, k,attr_type), k)
)
elif v is None:
addline(convert_none(k, v, attr))
addline(convert_none(k, v, attr,attr_type))
else:
raise TypeError('Unsupported data type: %s (%s)' % (obj, type(obj).__name__))
return ''.join(output)

def convert_list(items, ids, parent):
def convert_list(items, ids, parent,attr_type=True):
"""Converts a list into an XML string."""
logging.info('Inside convert_list()')
output = []
Expand All @@ -138,62 +148,91 @@ def convert_list(items, ids, parent):
'id': '%s_%s' % (this_id, i+1)
}
if type(item) in (int, float, str, unicode):
addline(convert_kv('item', item, attr))
addline(convert_kv('item', item, attr,attr_type))
elif hasattr(item, 'isoformat'): # datetime
addline(convert_kv('item', item.isoformat(), attr))
addline(convert_kv('item', item.isoformat(), attr,attr_type))
elif type(item) == bool:
addline(convert_bool('item', item, attr))
addline(convert_bool('item', item, attr,attr_type))
elif isinstance(item, dict):
addline('<item type="dict">%s</item>' % (convert_dict(item, ids, parent)))
if not attr_type:
addline('<item>%s</item>' % (convert_dict(item, ids, parent,attr_type)))
else:
addline('<item type="dict">%s</item>' % (convert_dict(item, ids, parent,attr_type)))
elif type(item) in (list, set, tuple) or isinstance(item, collections.Iterable):
addline('<item type="list"%s>%s</item>' % (make_attrstring(attr), convert_list(item, ids, 'item')))
if not attr_type:
addline('<item %s>%s</item>' % (make_attrstring(attr), convert_list(item, ids, 'item',attr_type)))
else:
addline('<item type="list"%s>%s</item>' % (make_attrstring(attr), convert_list(item, ids, 'item',attr_type)))
elif item == None:
addline(convert_none('item', None, attr))
addline(convert_none('item', None, attr,attr_type))
else:
raise TypeError('Unsupported data type: %s (%s)' % (item, type(item).__name__))
return ''.join(output)

def convert_kv(key, val, attr={}):
def convert_kv(key, val, attr={},attr_type=True):
"""Converts an int, float or string into an XML element"""
logging.info('Inside convert_kv(): k=%s, type(v) is: %s' % (key, type(val).__name__))
key = key.replace(' ', '_') # replace spaces with underscores
if key_is_valid_xml(key) == False:
attr['name'] = key
key = "key"
attrstring = make_attrstring(attr)
return '<%s type="%s"%s>%s</%s>' % (
key, type(val).__name__ if type(val).__name__ != 'unicode' else 'str',
attrstring, xml_escape(val), key
)
if not attr_type:
return '<%s %s>%s</%s>' % (
key, attrstring, xml_escape(val), key
)
else:
return '<%s type="%s"%s>%s</%s>' % (
key, type(val).__name__ if type(val).__name__ != 'unicode' else 'str',
attrstring, xml_escape(val), key
)


def convert_bool(key, val, attr={}):

def convert_bool(key, val, attr={},attr_type=True):
"""Converts a boolean into an XML element"""
logging.info('Inside convert_bool(): key=%s, type(val) is: %s' % (key, type(val).__name__))
key = key.replace(' ', '_') # replace spaces with underscores
if key_is_valid_xml(key) == False:
attr['name'] = key
key = "key"
attrstring = make_attrstring(attr)
return '<%s type="bool"%s>%s</%s>' % (key, attrstring, unicode(val).lower(), key)
if not attr_type:
return '<%s %s>%s</%s>' % (key, attrstring, unicode(val).lower(), key)
else:
return '<%s type="bool"%s>%s</%s>' % (key, attrstring, unicode(val).lower(), key)

def convert_none(key, val, attr={}):
def convert_none(key, val, attr={},attr_type=True):
"""Converts a null value into an XML element"""
logging.info('Inside convert_none(): key=%s' % (key))
key = key.replace(' ', '_') # replace spaces with underscores
if key_is_valid_xml(key) == False:
attr['name'] = key
key = "key"
attrstring = make_attrstring(attr)
return '<%s type="null"%s></%s>' % (key, attrstring, key)
if not attr_type:
return '<%s %s></%s>' % (key, attrstring, key)
else:
return '<%s type="null"%s></%s>' % (key, attrstring, key)

def dicttoxml(obj, root=True, ids=False):
"""Converts a python object into XML"""
def dicttoxml(obj, root=True, ids=False,attr_type=True):
"""Converts a python object into XML
attr_type is used to specify if data type for each element should be included in the resulting xml.
By default, it is set to True.
"""
logging.info('Inside dicttoxml(): type(obj) is: %s' % (type(obj).__name__))
output = []
addline = output.append
if root == True:
addline('<?xml version="1.0" encoding="UTF-8" ?>')
addline('<root>%s</root>' % (convert(obj, ids, parent='root')))
if not attr_type:
addline('<?xml version="1.0" encoding="UTF-8" ?>')
addline('<root>%s</root>' % (convert(obj, ids, parent='root',attr_type=False)))
else:
addline('<?xml version="1.0" encoding="UTF-8" ?>')
addline('<root>%s</root>' % (convert(obj, ids, parent='root',attr_type=True)))
else:
addline(convert(obj, ids, parent=''))
if not attr_type:
addline(convert(obj, ids, parent='',attr_type=False))
else:
addline(convert(obj, ids, parent='',attr_type=True))
return ''.join(output)