2013-04-29 47 views
0

我正在使用xml.ElementTree遍歷python列表並將其寫入樹形結構中的xml文件。以下是以下代碼並遵循所需的輸出。可以any1請幫助我!xml元素樹:無法獲得預期的輸出

import xml.etree.ElementTree as ET 
sample = ['germany','India','USA','srilanka'] 

root = ET.Element("root") 
data = ET.SubElement(root, "data") 
title = ET.SubElement(data, "country") 
for a in sample: 
    title.text = a 
    data.append('title') 

tree = ET.ElementTree(root) 
tree.write("page.xml") 

電流輸出

- <root> 
     <data> 
      <country>srilanka</country> 
      <country>srilanka</country> 
      <country>srilanka</country> 
      <country>srilanka</country> 
      <country>srilanka</country> 
     </data> 
    </root> 

Expected output 
    <root> 
     <data> 
      <country>germany</country> 
      <country>india</country> 
      <country>usa</country> 
      <country>srilanka</country> 
     </data> 
    </root> 

我需要以這種方式輸出...幫助我! 在此先感謝!

回答

0

問題是,你總是追加相同的元素,它被修改以反映最終值。請注意,該附加功能與引用一起使用,而不是您所期望的快照副本。最簡單的修復方法是爲每個國家創建一個新的子元素實例。

+0

非常感謝你!!# – Sangamesh 2013-04-29 08:22:05