0
我是Python新手。我想做遞歸函數來從複雜字典中生成xml(即詞典的字典,例如如何從Python中的複雜詞典中製作xml
dataDict = {'item1': 'this in item1', 'item2': 'this in item2', 'item3': 'this is item3'} rootDict = {'name': 'Daud', 'code': 'MC111011', 'data': dataDict}
)。
這是我已經試過了,
from lxml import etree
def dict_to_xml(dictData):
for key,val in dictData.items():
if isinstance(val, type(dict)):
child = dict_to_xml(val)
if child is not None:
yield from child
else:
yield key, val
child = etree.Element(key)
child.text = str(val)
return child
# create XML
dataDict = {'item1': 'this in item1', 'item2': 'this in item2', 'item3': 'this is item3'}
rootDict = {'data': dataDict}
for key, value in rootDict.items():
if isinstance(value, type(dict)):
childElement = dict_to_xml(value)
else:
childElement = etree.Element(key)
childElement.text = str(value)
root = etree.Element('root')
root.append(etree.Element('child'))
# another child with text
root.append(childElement)
# pretty string
s = etree.tostring(root, pretty_print=True)
print(s)
我得到以下輸出
b"<root>\n <child/>\n <data>{'item1': 'this in item1', 'item2': 'this in item2', 'item3': 'this is item3'}</data>\n</root>\n"
請指引我,我錯過了什麼。謝謝
@ user6159419請不要忘記,讓我們知道是否能解決你的問題,因爲它會幫助其他人的情況下,他們面臨着類似的問題在未來。 – Prem