Skip to content

Instantly share code, notes, and snippets.

@mmarignoli
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmarignoli/7e445841061bb366b7e2 to your computer and use it in GitHub Desktop.
Save mmarignoli/7e445841061bb366b7e2 to your computer and use it in GitHub Desktop.
Dicttoxml extend
from dicttoxml import *
def convert_list(items, ids, parent, attr_type):
"""Converts a list into an XML string."""
logging.info('Inside convert_list()')
output = []
addline = output.append
if ids:
this_id = get_unique_id(parent)
for i, item in enumerate(items):
logging.info('Looping inside convert_list(): item="%s", type="%s"' % (item, type(item).__name__))
attr = {} if not ids else { 'id': '%s_%s' % (this_id, i+1) }
if type(item) in (int, float, long, str, unicode):
addline(convert_kv('item', item, attr_type, attr))
elif hasattr(item, 'isoformat'): # datetime
addline(convert_kv('item', item.isoformat(), attr_type, attr))
elif type(item) == bool:
addline(convert_bool('item', item, attr_type, attr))
elif isinstance(item, dict):
if not attr_type:
addline('<segment>%s</segment>' % (convert_dict(item, ids, parent, attr_type)))
else:
addline('<segment type="dict">%s</segment>' % (convert_dict(item, ids, parent, attr_type)))
elif type(item) in (list, set, tuple) or isinstance(item, collections.Iterable):
if not attr_type:
addline('<segment %s>%s</segment>' % (make_attrstring(attr), convert_list(item, ids, 'item', attr_type)))
else:
addline('<segment type="list"%s>%s</segment>' % (make_attrstring(attr), convert_list(item, ids, 'item', attr_type)))
elif item == None:
addline(convert_none('item', None, attr_type, attr))
else:
raise TypeError('Unsupported data type: %s (%s)' % (item, type(item).__name__))
return ''.join(output)
from libs.dicttoxml_fast.dicttoxml_fast import dicttoxml
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment