1.修改节点的属性和内容

  1. from xml.etree import ElementTree as ET
  2. content = """
  3. <data>
  4. <country name="Liechtenstein">
  5. <rank>2</rank>
  6. <year>2023</year>
  7. <gdppc>141100</gdppc>
  8. <neighbor direction="E" name="Austria" />
  9. <neighbor direction="W" name="Switzerland" />
  10. </country>
  11. <country name="Panama">
  12. <rank>69</rank>
  13. <year>2026</year>
  14. <gdppc>13600</gdppc>
  15. <neighbor direction="W" name="Costa Rica" />
  16. <neighbor direction="E" name="Colombia" />
  17. </country>
  18. </data>
  19. """
  20. root = ET.XML(content)
  21. # 修改节点内容
  22. year = root.find('country').find('year')
  23. year.text = '2021'
  24. # 测试一下是否修改成功
  25. print(year.text)
  26. # 修改节点属性
  27. neibor1 = root.find('country').find('neighbor')
  28. neibor1.set('name','China')
  29. # 测试一下是否成功
  30. print(neibor1.attrib)
  31. # 保存修改
  32. tree = ET.ElementTree(root)
  33. tree.write("new.xml", encoding='utf-8')

2.删除节点

  1. from xml.etree import ElementTree as ET
  2. content = """
  3. <data>
  4. <country name="Liechtenstein">
  5. <rank>2</rank>
  6. <year>2023</year>
  7. <gdppc>141100</gdppc>
  8. <neighbor direction="E" name="Austria" />
  9. <neighbor direction="W" name="Switzerland" />
  10. </country>
  11. <country name="Panama">
  12. <rank>69</rank>
  13. <year>2026</year>
  14. <gdppc>13600</gdppc>
  15. <neighbor direction="W" name="Costa Rica" />
  16. <neighbor direction="E" name="Colombia" />
  17. </country>
  18. </data>
  19. """
  20. root = ET.XML(content)
  21. # 删除country第一个节点
  22. root.remove(root.find('country'))
  23. # 测试节点是否删除
  24. print(root.find('country').attrib)
  25. # 保存修改
  26. tree = ET.ElementTree(root)
  27. tree.write('new2.xml',encoding = 'utf-8')