我是 Python/ ElementTree的新手。我有以下 XML 示例:
<users>
<user username="admin" fullname="admin" password="" uid="1000"/>
<user username="user1" fullname="user1" password="" grant_admin_rights="yes"><group>my_group</group><group>group_2</group></user>
</users>
我想将以下内容附加到这个现有的 XML:
<user username="+username+" password="+password+"><group>+newgroup+</group></user>
所以我的最终输出应该是这样的:
<users>
<user username="admin" fullname="admin" password="" uid="1000"/>
<user username="user1" fullname="user1" password="" grant_admin_rights="yes"><group>my_group</group><group>group_2</group></user>
<user username="+username+" password="+password+"><group>+newgroup+</group></user>
</users>
这是我的尝试:
import sys
import xml.etree.ElementTree as ET
class Users(object):
def __init__(self, users=None):
self.doc = ET.parse("users.xml")
self.root = self.doc.getroot()
def final_xml(self):
root_new = ET.Element("users")
for child in self.root:
username = child.attrib['username']
password = child.attrib['password']
user = ET.SubElement(root_new, "user")
user.set("username",username)
user.set("password",password)
try:
fullname = child.attrib['fullname']
except KeyError:
pass
for g in child.findall("group"):
group = ET.SubElement(user,"group")
group.text = g.text
tree = ET.ElementTree(root_new)
tree.write(sys.stdout)