for name in root.findall('age'): age = int(name.find('age').text) if age > 50 : root.remove() tree.write('xml_test.xml')
新建 xml 树
1 2 3 4 5 6 7 8 9
new_xml = ET.Element('namelist') name = ET.SubElement(new_xml,'name',attrib={"enrolled":"yes"}) age = ET.SubElement(name,"age",attrib={"checked":"no"}) sex = ET.SubElement(name,"sex") age.text='33'
et = ET.ElementTree(new_xml) et.write("test.xml",encoding="utf-8",xml_declaration=True) ET.dump(new_xml)