<person>
<user name="david" password="super"><groups>meganfox</groups></user>
<user name="alen" password="boss"><groups>marvik</groups></user>
</person>
我喜欢获取 "groups" 的文本值。但它总是没有。
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']
for groups in child.findall('groups'): #this is not working for me :(
gpvalue = groups.text
user = ET.SubElement(root_new, "user") # create subelement in cycle!
group = ET.SubElement(user, "groups")
user.set("name",name)
user.set("password",password)
group.text = gpvalue
tree = ET.ElementTree(root_new)
tree.write("new.xml")
import sys
tree.write(sys.stdout)
输出得到:(
<person>
<user name="david" password="super"></groups></user>
<user name="alen" password="boss"></groups></user>
</person>
没有组文本值。它的打印只有一个封闭的组。请检查输出