0
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:
    username             = child.attrib['username']
    password             = child.attrib['password']
    grant_admin_rights   = child.attrib['grant_admin_rights']
    create_private_share = child.attrib['create_private_share']
    uid                  = child.attrib['uid']



root  = ET.Element("users")
user  = ET.SubElement(root, "user")
user.set("username",username)
user.set("password",password)
user.set("grant_admin_rights",grant_admin_rights)
user.set("create_private_share",create_private_share)
user.set("uid",uid)

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

print myxml 

我的输入xml:-

<users>
<user username="admin" fullname="admin" password="admin" create_private_share="yes" remote_access="yes" grant_admin_rights="yes" enable_encrypt_share="yes" volume="DataVolume5" uid="1000"></user>
<user username="os" fullname="sp" password="sp" grant_admin_rights="no" create_private_share="no" uid="1000" ></user>
<user username="us" fullname="sp" password="sp" grant_admin_rights="no" create_private_share="no" uid="1000" ></user>
</users>

输出这段代码:

<user create_private_share="no" grant_admin_rights="no" password="sp" uid="1000" username="us" />

我试图获得确切的 xml 作为我的输入 xml,但目前它迭代所有子项,但仅输出,最后一个?我如何迭代所有子项并打印确切的 xml。

在我的情况下,打印也没有工作,它显示无。

我希望我的输出应该是这样的:

<users>
<user username="admin" fullname="admin" password="admin" create_private_share="yes" remote_access="yes" grant_admin_rights="yes" enable_encrypt_share="yes" volume="DataVolume5" uid="1000"></user>
<user username="os" fullname="sp" password="sp" grant_admin_rights="no" create_private_share="no" uid="1000" ></user>
<user username="us" fullname="sp" password="sp" grant_admin_rights="no" create_private_share="no" uid="1000" ></user>
</users>

提前致谢 :)

4

1 回答 1

2

你的逻辑有些问题。只会使用循环的最后一个值。您应该尝试在每次循环时创建节点,然后加入结果并将它们写入文件

于 2012-10-30T08:47:56.113 回答