I have nested python dictionary like this.
d = {}
d[a] = b
d[c] = {1:2, 2:3}
I am trying to recursively convert the nested dictionary into an xml format since there can be more nested dictionary inside such as d[e] = {1:{2:3}, 3:4}
. My desired XML format is like this
<root>
<a>b</a>
<c>
<1>2</1>
<2>3</3>
</c>
</root>
I have so far this python code to handle nested xml using lxml library. But it doesn't give me the desired output.
def encode(node, Dict):
if len(Dict) == 0:
return node
for kee, val in Dict.items():
subNode = etree.SubElement(node, kee)
del msgDict[kee]
if not isinstance(val, dict):
subNode.text = str(val)
else:
return encode(subNode, val)
Any help is appreciated. Thank you.
The way you recall encode does not look correct. Maybe this helps. For simplicity I just append stuff to a list (called l
). Instead, you should do your etree.SubElement(...)
.
def encode(D, l=[]):
for k, v in D.items():
if isinstance(v, dict):
l2 = [k]
encode(v, l2)
l.append(l2)
else:
l.append([k, v])
I found the bug in my code, which is I didn't return the recursive call back to the original loop. After going inside nested elements, it "returns" and doesn't get back to original loop. Instead of return encode(subNode, val)
, saving in a variable element = encode(subNode, val)
solves the problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.