簡體   English   中英

每次我在python中循環時如何創建節點

[英]How to create a nodes every time i go through the loop in 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 

代碼的輸出只包含loop :(

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

每次循環時如何創建節點,然后將結果加入並將其寫入文件。 我真的是一個初學者,請給我詳細說明。 非常感謝你 。

嘗試下一個。 您對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)

“每次通過循環創建節點”的技巧是在循環內部創建節點。 你要:

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對空格敏感。 如果您不縮進最后三行,則它們不屬於循環的一部分。

您將覆蓋從根讀取的樹。 附加到您閱讀的內容

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顯然沒有返回

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM