2012-07-31 124 views
-2

我想從具有以下結構的字典中的值中創建XML字符串。從根到字符串的鍵數(字典深度)是不確定的,範圍從1到?。將字典轉換爲XML

'modes': { 'P': { 'S': { u'01': u'Some Text A.', 
           u'02': u'Some Text B.', 
           u'03': u'Some Text C.', 
           u'04': u'Some Text D.', 
           u'05': u'Some Text E.', 
           u'06': u'Some Text F.'}, 
        'U': { u'01': u'Some Text G.', 
           u'02': u'Some Text H.'}}, 
      'R': { 'S': { u'01': u'Some Text I.', 
           u'02': u'Some Text J.', 
           u'03': u'Some Text K.', 
           u'04': u'Some Text M.', 
           u'05': u'LSome Text N.'}, 
        'U': { u'01': u'Some Text O.', 
           u'02': u'Some Text P.', 
           u'03': u'Some Text Q.'}}} 

輸出後,我的一個例子是:

<modes> 
    <property P> 
    <property S> 
     <text> 
     <order>'01'</order> 
     <string>'Some Text A.'</string> 
     </text> 
     <text> 
     <order>'02'</order> 
     <string>'Some Text B.'</string> 
     </text> 
     ... 
    </property S> 

    <property U> 
     <text> 
     <order>'01'</order> 
     <string>'Some Text G.'</string> 
     </text> 
     <text> 
     <order>'02'</order> 
     <string>'Some Text H.'</string> 
     </text>  
    </property U> 
    </property P> 

    <property R> 
     <property S> 
     <text> 
     <order>'01'</order> 
     <string>'Some Text I.'</string> 
     </text> 
     <text> 
     <order>'02'</order> 
     <string>'Some Text J.'</string> 
     </text> 
     ... 
    </property S> 

    <property U> 
     <text> 
     <order>'01'</order> 
     <string>'Some Text O.'</string> 
     </text> 
     <text> 
     <order>'02'</order> 
     <string>'Some Text P.'</string> 
     </text>  
     ... 
    </property U> 
    </property R> 
</modes> 

我更感興趣的是如何遍歷結構,這樣我可以把孩子在父母的權利,而而不是XML的確切輸出。任何有關可能改變數據結構的建議也將被讚賞,因爲我覺得我已經把自己打入了一個角落! 謝謝朱利安

+0

」不是有效的XML。除此之外:你到目前爲止嘗試過什麼?這是直接使用嵌套循環遍歷嵌套的字典結構...這是作業嗎? – 2012-07-31 04:15:16

+0

有效xml = 2012-07-31 04:17:20

回答

1

他們的方式,我發現是使用,如果詞典[關鍵]是不是一個字典,將打印鍵,值遞歸函數,否則打印遞歸調用

def _dict_to_xml(dictionary): 
    returnlist = [] 
    for key in dictionary: 
     if isinstance(dictionary[key],dict): 
      returnlist.append(r'<node name="{name}">'.format(name=key)) 
      returnlist.append(_dict_to_xml(dictionary[key])) 
      returnlist.append(r'</node>') 
     else: 
      returnlist.append(r'<order>{key}</order>'.format(key=key)) 
      returnlist.append(r'<string>{value}</string>'.format(value = dictionary[key])) 
    return '\n'.join(returnlist) 


def dict_to_xml(dictionary): 
    return '<?xml version="1.0"?>\n'+_dict_to_xml(dictionary)+'</xml>' 
+0

謝謝你這個作品。 – knowingpark 2012-07-31 04:51:26

+0

我不明白你爲什麼選擇使用列表來累積輸出字符串而不是字符串? – knowingpark 2012-07-31 05:49:57

+0

字符串是不可變的,因此str1 + = str2意味着另一個字符串被創建,代表str1 + str2,str1現在引用新創建的字符串。使用string.join可以解決這個問題。 – 2012-07-31 05:52:52

1

寫一個函數,將採取當前結構以及節點添加孩子。在結構中遇到遞歸時,使用新節點和子結構遞歸函數。