在Python中读取XML文件,你可以使用Python标准库中的`xml.etree.ElementTree`模块,也可以选择第三方库`lxml`。以下是使用`xml.etree.ElementTree`模块读取XML文件的示例代码:
import xml.etree.ElementTree as ET加载XML文件tree = ET.parse('example.xml')获取根元素root = tree.getroot()遍历根元素下的所有子元素for child in root:输出子元素的标签和文本内容print(child.tag, child.text)
如果你需要更高级的功能,比如格式化输出XML文档,可以使用`xml.dom.minidom`模块:
from xml.dom import minidom打开XML文档dom = minidom.parse('example.xml')获取文档元素对象root = dom.documentElement输出根节点的名称、值、类型print(root.nodeName, root.nodeValue, root.nodeType, root.ELEMENT_NODE)

`lxml`库提供了更快的解析速度和更丰富的功能,安装`lxml`可以使用pip:
pip install lxml
使用`lxml`读取XML文件的示例代码如下:
from lxml import etree加载XML文件tree = etree.parse('example.xml')获取根元素root = tree.getroot()遍历根元素下的所有子元素for child in root:输出子元素的标签和文本内容print(child.tag, child.text)
请根据你的具体需求选择合适的模块和方法。
