我喜欢在每次循环时创建一个节点。但目前只会使用循环的最后一个值。我如何使用 python 来实现这一点。以下是我的例子。
我的xml:-
<person>
<user name="david" password="super"></user>
<user name="alen" password="boss"></user>
<user name="windeesal" password="sp"></user>
</person>
蟒蛇代码:
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>
每次我通过循环时如何创建节点然后加入结果并将它们写入文件。?我真的是一个初学者,请给我一个详细的解释。非常感谢你 。