From c63a201222f37fb16402c8ae2fa990d40d449104 Mon Sep 17 00:00:00 2001 From: Josue Kouka Date: Mon, 29 May 2017 09:56:48 +0200 Subject: [PATCH 6/7] cityweb: add json to xml converter function (#15883) --- passerelle/contrib/cityweb/utils.py | 63 ++++++++++++++++++++++++++++++++++++- 1 file changed, 62 insertions(+), 1 deletion(-) diff --git a/passerelle/contrib/cityweb/utils.py b/passerelle/contrib/cityweb/utils.py index 4c8c209..088fc9f 100644 --- a/passerelle/contrib/cityweb/utils.py +++ b/passerelle/contrib/cityweb/utils.py @@ -15,14 +15,55 @@ import os import zipfile +from xml.etree import ElementTree as etree +from xml.dom import minidom from django.core.files.storage import default_storage +class ElementFactory(etree.Element): + + def __init__(self, *args, **kwargs): + self.text = kwargs.pop('text', None) + namespace = kwargs.pop('namespace', None) + if namespace: + super(ElementFactory, self).__init__( + etree.QName(namespace, args[0]), **kwargs + ) + self.namespace = namespace + else: + super(ElementFactory, self).__init__(*args, **kwargs) + + def __unicode__(self): + if isinstance(self.tag, (etree.QName,)): + return self.tag.text + return self.tag + + __repr__ = __str__ = __unicode__ + + def append(self, element, allow_new=True): + if not allow_new: + if isinstance(element.tag, etree.QName): + found = self.find(element.tag.text) + else: + found = self.find(element.tag) + if found is not None: + return self + super(ElementFactory, self).append(element) + return self + + def to_pretty_xml(self): + raw = etree.tostring(self) + parsed = minidom.parseString(raw) + return parsed.toprettyxml(indent='\t') + + def flatten_payload(*subs): result = {} for sub in subs: - result.update(sub) # priority on last sub dict + if not isinstance(sub, (dict,)): + continue + result.update(sub) # priority to the last sub dict return result @@ -40,3 +81,23 @@ def zipdir(path): fpath = os.path.join(root, f) zipf.write(fpath, os.path.basename(fpath)) return archname + + +def json_to_xml(path, value, parent, namespace=None): + if isinstance(path, list) and len(path) > 1: + if namespace: + tag = '{%s}%s' % (namespace, path[0]) + else: + tag = path[0] + # parent_child = parent.find('{%s}%s' % (namespace, path[0])) + parent_child = parent.find(tag) + if parent_child is not None: + element = parent_child + path.pop(0) + else: + element = ElementFactory(path.pop(0), namespace=namespace) + element.append(json_to_xml(path, value, element, namespace=namespace), + allow_new=False) + else: + element = ElementFactory(path[0], text=value, namespace=namespace) + return element -- 2.11.0