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")

此代码的输出:-

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

但我试图让它像这样:-

<users>

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

</users>

而不是这个<user />,我正在尝试<user> <group>fgfg</group> </user>。谢谢

4

1 回答 1

2

试试SubElement工厂功能:

group = SubElement(user, "group")
# ...
于 2012-10-30T08:56:35.777 回答