一.导入ET模块

  1. from xml.etree import ElementTree as ET

获取根节点,分为:从文件获取根节点和从文本获取根节点

二.从文件获取根节点

  1. # 先导入模块
  2. from xml.etree import ElementTree as ET
  3. # 从文本路径获取文本对象
  4. file = ET.parse(filepath)
  5. # 文本对象获得根节点
  6. root = file.getroot()

三.从文本获取根节点

  1. from xml.etree import ElementTree as ET
  2. # 下列是文本字符串
  3. content = """
  4. <data>
  5. <country name="Liechtenstein">
  6. <rank updated="yes">2</rank>
  7. <year>2023</year>
  8. <gdppc>141100</gdppc>
  9. <neighbor direction="E" name="Austria" />
  10. <neighbor direction="W" name="Switzerland" />
  11. </country>
  12. <country name="Panama">
  13. <rank updated="yes">69</rank>
  14. <year>2026</year>
  15. <gdppc>13600</gdppc>
  16. <neighbor direction="W" name="Costa Rica" />
  17. <neighbor direction="E" name="Colombia" />
  18. </country>
  19. </data>
  20. """
  21. # 直接从文本字符串,获取根节点
  22. root = ET.XML(content)