0

I am trying to create a reliable and safe object to XML library. Got something from stackoverflow but have some issues that I am trying to improvise on. Can someone help me resolve the recursive factiorial like loop problem to avoid duplicates?

import json
from xml.etree.ElementTree import Element, tostring
def obj2xml(tag, d):
    """
    Convert python dictionary to xml
    :param tag:
    :param d:
    :return:
    """
    elem = Element(tag)
    if(isinstance(d,list)):
        for val in d:
            if(isinstance(val,dict)) or (isinstance(val,list)):
                val=obj2xml(tag,val)
                elem.append(val)
            else:
                elem.append(Element(str(val)))
        return elem
    if(isinstance(d,str)):
        elem.text = str(d)
        return elem
    for key, val in d.items():
        child = Element(key.replace("/", ":"))  # For situations where we are using / as prefix like sip/24
        if(isinstance(val,dict)) or (isinstance(val,list)):
            val = obj2xml(key,val)
            child.append(val)
        else:
            child.text = str(val)
        elem.append(child)
    return elem


print(tostring(obj2xml("x",[1,2])))
print(tostring(obj2xml("x",{"z":{"a":"b"}})))

Currently it prints

<x><1 /><2 /></x>
<x><z><z><a>b</a></z></z></x> 

I need for it not loop element z twice without complicating the code. DO you all have a good suggestion to optimally do this. This code is already a little too many "ifs" and "loops" - I am trying to keep it simple and efficient as possible.

thanks vijay

Vijay
  • 157
  • 1
  • 9
  • How can we possibly help with no data input or desired output? – Parfait Sep 15 '17 at 18:07
  • Sorry for not being clear! The sample data input is part of the code : first example: [1,2] Second example : {"z":{"a":"b"}} Both of these are part of an XML object "x" I have looked at the Serialize Python dictionary to XML example but not exactly finding the best solutions of the examples. Either dependency on a library I dont have or a risk naive XML that could fail easily when transitioning from an object to XML. – Vijay Sep 15 '17 at 18:35

0 Answers0