一.导入ET模块
from xml.etree import ElementTree as ET
获取根节点,分为:从文件获取根节点和从文本获取根节点
二.从文件获取根节点
# 先导入模块from xml.etree import ElementTree as ET# 从文本路径获取文本对象file = ET.parse(filepath)# 文本对象获得根节点root = file.getroot()
三.从文本获取根节点
from xml.etree import ElementTree as ET# 下列是文本字符串content = """<data> <country name="Liechtenstein"> <rank updated="yes">2</rank> <year>2023</year> <gdppc>141100</gdppc> <neighbor direction="E" name="Austria" /> <neighbor direction="W" name="Switzerland" /> </country> <country name="Panama"> <rank updated="yes">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)