1.修改节点的属性和内容
from xml.etree import ElementTree as ET
content = """
<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 ET
content = """
<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')