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