0
私はPythonが初めてです。複雑辞書(辞書辞書、例えばPythonで複雑な辞書からxmlを作る方法
dataDict = {'item1': 'this in item1', 'item2': 'this in item2', 'item3': 'this is item3'} rootDict = {'name': 'Daud', 'code': 'MC111011', 'data': dataDict}
)からxmlを生成するための再帰関数を作りたいと思います。
これは私が試してみました何で、
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 @ plsはそれはあなたの問題を解決した場合はお知らせすることを忘れないでください。 – Prem