-1

我喜欢在每次循环时创建一个节点。但目前只会使用循环的最后一个值。我如何使用 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>

每次我通过循环时如何创建节点然后加入结果并将它们写入文件。?我真的是一个初学者,请给我一个详细的解释。非常感谢你 。

4

3 回答 3

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)
于 2012-11-01T08:07:32.470 回答
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 对空格敏感。如果你不缩进底部的三行,它们就不是循环的一部分。

于 2012-11-01T08:14:38.780 回答
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 显然返回 None

于 2012-11-01T07:52:11.423 回答