ElementTree是Python处理XML的常用库,支持从文件或字符串加载数据,通过find、findall和iter方法遍历元素,可修改内容并保存,适用于解析配置文件和接口数据。

Python解析XML文件最常用的方式是使用内置的xml.etree.ElementTree库(简称ElementTree)。它轻量、易用,适合处理结构清晰的XML数据。本文将介绍ElementTree的基本用法,并通过实际例子帮助你快速掌握。
ElementTree支持从字符串或文件加载XML。使用ET.parse()读取文件,或ET.fromstring()解析字符串。
.getroot()获取根元素示例XML文件(data.xml):
<?xml version="1.0"?>
<library>
<book id="1">
<title>Python入门</title>
<author>张三</author>
<price>50.0</price>
</book>
<book id="2">
<title>数据分析实战</title>
<author>李四</author>
<price>68.5</price>
</book>
</library>
代码加载方式:
立即学习“Python免费学习笔记(深入)”;
import xml.etree.ElementTree as ET
<h1>从文件读取</h1><p>tree = ET.parse('data.xml')
root = tree.getroot()</p><h1>或从字符串读取</h1><p>xml_str = """<library>...</library>"""
root = ET.fromstring(xml_str)</p>Element对象提供多种方法访问子元素和属性。常用方法包括.find()、.findall()和.iter()。
示例:提取所有书名和作者
for book in root.findall('book'):
title = book.find('title').text
author = book.find('author').text
book_id = book.get('id') # 获取属性
print(f"ID: {book_id}, 书名: {title}, 作者: {author}")
你可以动态修改元素内容、添加属性或新节点,并将结果写回文件。
示例:给每本书加一个分类标签
for book in root.findall('book'):
category = ET.SubElement(book, 'category')
if 'Python' in book.find('title').text:
category.text = '编程'
else:
category.text = '数据科学'
<h1>保存到新文件</h1><p>tree.write('updated_data.xml', encoding='utf-8', xml_declaration=True)</p>生成的XML会包含新增的<category>节点。
当XML包含命名空间时,需在标签前加上命名空间前缀。
例如,带有命名空间的XML:
<root xmlns:ns="http://example.com/ns"> <ns:item>内容</ns:item> </root>
查找时需完整写法:
namespace = {'ns': 'http://example.com/ns'}
item = root.find('ns:item', namespace)
if item is not None:
print(item.text)
基本上就这些。ElementTree足够应对大多数日常XML处理需求,不复杂但容易忽略细节,比如.getroot()和.findall()的作用范围。熟练掌握后,读取配置文件、解析接口返回数据都会变得轻松。
以上就是Python如何解析xml文件? ElementTree库使用教程与实例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号