2017-08-25 26 views
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" 

私が行方不明です何私を導いてください。ありがとう

答えて

0

これは役に立ちます。

from dicttoxml import dicttoxml 

dataDict = {'item1': 'this in item1', 'item2': 'this in item2', 'item3': 'this is item3'} 
rootDict = {'name': 'Daud', 'code': 'MC111011','data': dataDict} 

xml = dicttoxml(rootDict, custom_root='myXML', attr_type=False) 
print xml 

出力は次のようになります。それは、彼らが将来的に同様の問題に直面した場合に他の人を助けるだろうと

<myXML><code>MC111011</code><data><item2>this in item2</item2><item3>this is item3</item3><item1>this in item1</item1></data><name>Daud</name></myXML> 
+0

user6159419 @ plsはそれはあなたの問題を解決した場合はお知らせすることを忘れないでください。 – Prem

関連する問題