python读取xml文件的方法有多种,主要有以下几种:
使用ElementTree库:ElementTree库是Python内置的解析XML文件的库,可以通过它来读取和操作XML文件。示例代码如下:import xml.etree.ElementTree as ETtree = ET.parse('file.xml')root = tree.getroot()# 遍历所有的子节点for child in root: print(child.tag, child.attrib)# 获取特定子节点的值value = root.find('child_node').text# 修改特定子节点的值root.find('child_node').text = 'new_value'# 保存修改后的XML文件tree.write('new_file.xml')使用lxml库:lxml库是一个功能强大的解析和处理XML文件的库,速度较快。示例代码如下:from lxml import etreetree = etree.parse('file.xml')root = tree.getroot()# 遍历所有的子节点for child in root: print(child.tag, child.attrib)# 获取特定子节点的值value = root.find('child_node').text# 修改特定子节点的值root.find('child_node').text = 'new_value'# 保存修改后的XML文件tree.write('new_file.xml', pretty_print=True, encoding='utf-8')使用xml.dom.minidom库:xml.dom.minidom库是Python内置的一个轻量级的DOM解析器,可以用来读取和操作XML文件。示例代码如下:from xml.dom import minidomdom = minidom.parse('file.xml')root = dom.documentElement# 遍历所有的子节点for child in root.childNodes: if child.nodeType == child.ELEMENT_NODE: print(child.tagName, child.attributes.items())# 获取特定子节点的值value = root.getElementsByTagName('child_node')[0].firstChild.nodeValue# 修改特定子节点的值node = root.getElementsByTagName('child_node')[0]node.firstChild.replaceWholeText('new_value')# 保存修改后的XML文件with open('new_file.xml', 'w') as f: dom.writexml(f, addindent=' ', newl='\n', encoding='utf-8')这些方法都可以读取XML文件并提取、修改其中的数据。具体选择哪种方法取决于个人需求和习惯。