2012-11-01 92 views
-1

我喜歡每當我經歷一個循環時創建一個節點。但是現在只會使用循環的最後一個值。我怎樣才能實現這一點使用python。以下是我的例子。如何在每次通過python循環時創建一個節點

我的XML: -

<person> 
<user name="david" password="super"></user> 
<user name="alen" password="boss"></user> 
<user name="windeesal" password="sp"></user> 
</person> 

的Python代碼:

import xml.etree.ElementTree as ET 

doc = ET.parse("users.xml") 
root = doc.getroot() #Returns the root element for this tree. 
root.keys()   #Returns the elements attribute names as a list. The names are returned in an arbitrary order 
for child in root: 
    name = child.attrib['name'] 
    password = child.attrib['password'] 

root = ET.Element("person") 
user = ET.SubElement(root, "user") 
user.set("username",username) 
user.set("password",password) 

tree = ET.ElementTree(root) 
myxml = tree.write("new.xml") 

print myxml 

出把代碼包含環:(只有最後一個值

<person> 
<user password="sp" username="windeesal" /> 
</person> 

如何創建節點每當我經過循環,然後加入結果並將它們寫入文件。?真的是初學者請給我詳細的解釋。非常感謝你 。

回答

3

嘗試下一個。你對python的理解似乎很基本,所以我不確定要寫什麼關於問題。

請詢問您是否需要說明! :)

import xml.etree.ElementTree as ET 

doc = ET.parse("users.xml") 
root = doc.getroot() #Returns the root element for this tree. 
root_new = ET.Element("person") 
for child in root: 
    name    = child.attrib['name'] 
    password    = child.attrib['password'] 

    user = ET.SubElement(root_new, "user") # create subelement in cycle! 
    user.set("username",name)    # username variable is not declared 
    user.set("password",password) 

tree = ET.ElementTree(root_new) 
tree.write("new.xml") 

import sys 
tree.write(sys.stdout) 
+0

這是足夠的解釋,我哥們:),非常感謝。 –

1

您正在覆蓋在根中讀取的樹。附加到你讀到的內容

import xml.etree.ElementTree as ET 

doc = ET.parse("users.xml") 
root = doc.getroot() #Returns the root element for this tree. 
root.keys()   #Returns the elements attribute names as a list. The names are returned in an arbitrary order 
for child in root: 
    name    = child.attrib['name'] 
    password    = child.attrib['password'] 

user = ET.SubElement(root, "user") 
user.set("username",'test') 
user.set("password",'me') 

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

另請檢查new.xml的結果。 tree.write返回無明顯

+0

嗨Himanshu感謝budyy,它也似乎工作 –

+1

我不知道誰做它-1,但我標記它+1它的工作我,但只有一件事它不會打印的XML :(如lisu在他的回答中提到 –

+1

嘗試ET.dump(根) – Himanshu

2

訣竅「創建節點每次我經過一個循環時間」是創建節點循環。你想:

for child in root: 
    name  = child.attrib['name'] 
    password = child.attrib['password'] 

    user = ET.SubElement(root_new, "user") 
    user.set("username", name) 
    user.set("password", password) 

Python是空白敏感的。如果你不縮進最底下的三行,它們不是循環的一部分。

相關問題