1.修改节点的属性和内容
from xml.etree import ElementTree as ETcontent = """<data> <country name="Liechtenstein"> <rank>2</rank> <year>2023</year> <gdppc>141100</gdppc> <neighbor direction="E" name="Austria" /> <neighbor direction="W" name="Switzerland" /> </country> <country name="Panama"> <rank>69</rank> <year>2026</year> <gdppc>13600</gdppc> <neighbor direction="W" name="Costa Rica" /> <neighbor direction="E" name="Colombia" /> </country></data>"""root = ET.XML(content)# 修改节点内容year = root.find('country').find('year')year.text = '2021'# 测试一下是否修改成功print(year.text)# 修改节点属性neibor1 = root.find('country').find('neighbor')neibor1.set('name','China')# 测试一下是否成功print(neibor1.attrib)# 保存修改tree = ET.ElementTree(root)tree.write("new.xml", encoding='utf-8')
2.删除节点
from xml.etree import ElementTree as ETcontent = """<data> <country name="Liechtenstein"> <rank>2</rank> <year>2023</year> <gdppc>141100</gdppc> <neighbor direction="E" name="Austria" /> <neighbor direction="W" name="Switzerland" /> </country> <country name="Panama"> <rank>69</rank> <year>2026</year> <gdppc>13600</gdppc> <neighbor direction="W" name="Costa Rica" /> <neighbor direction="E" name="Colombia" /> </country></data>"""root = ET.XML(content)# 删除country第一个节点root.remove(root.find('country'))# 测试节点是否删除print(root.find('country').attrib)# 保存修改tree = ET.ElementTree(root)tree.write('new2.xml',encoding = 'utf-8')