2016-06-23 10 views
1

これはサンプルXMLです。PythonでXMLから辞書リストを作成

<?xml version="1.0" encoding="UTF-8"?> 
<Test plan_name="test"> 
    <Big bro="S7" sys="lolipop"> 
     <Work name="first"></Work> 
     <Work name="second"></Work> 
    </Big> 
    <Big bro="S6" sys="kitkat"> 
     <Work name="trird"></Work> 
     <Work name="fourth"></Work> 
    </Big> 
</Test> 

私の目標は、各仕事の名前で辞書を作成し、それをリストに保持することです。

これは私のサンプルコードです:

import xml.etree.ElementTree as ET 

tree = ET.parse(line[0].rstrip()+'/stack.xml') 
root = tree.getroot() 

total=[] 

for child in root.findall('Big'): 
    test=child.attrib 
    for children in child:  
    test.update(children.attrib) 
    total.append(test) 
print total 

予想される出力:

[{ '仲間': 'S7'、 'SYS': 'ロリポップ'、 '名前':「最初の'名前': '名前': '' '' '' '' 'S6' '' sys ':'キット ' '第三'}、{ '仲間': 'S6'、 'SYS': 'キットカット'、 '名前': '第四'}]

しかし、私の出力は次のようになります。

[{'bro': 'S7'、 'sys': 'lolipop'、 'name': 'second'}、{'bro': 'S7'、 'sys': 'lolipop' '名前': '兄': '兄': 'S6'、 'sys': 'kitkat'、 '名前': '4番'、 '' bro ':' S6 '、' sys ':' kitkat '、' name ':' fourth '}]

お願いします。 ありがとうございました

+0

を 'ET'変数とは何ですか? 'ElementTree'? –

+0

はい。 ETとしてのxml.etree.ElementTreeのインポートは上記になります。 – Sam

答えて

1

test dict in-placeを変更すると、以前に挿入された参照の合計が変更されます。
それを更新する前に、そのコピーを作成することで動作するはずです:

... 
for child in root.findall('Big'): 
    test=child.attrib 
    for children in child:  
    testCopy = dict(test) 
    testCopy.update(children.attrib) 
    total.append(testCopy) 
print(total) 
... 
関連する問題