ElementTree模块可解析和创建xml,通过parse读取文件,findall遍历元素,get获取属性,text获取文本,支持查找与构建树结构,并写入含中文编码的XML文件。

python 的 xml.etree.ElementTree(简称 ElementTree)模块提供了一种简单高效的方式来解析和创建 XML 数据。它将整个 XML 文档加载为一个树结构,便于遍历、查找和修改元素。
解析XML文档
使用 ElementTree.parse() 可以读取一个 XML 文件并返回根节点对象。
假设有如下 XML 文件 books.xml:
<library> <book id="1"> <title>Python入门</title> <author>张三</author> </book> <book id="2"> <title>数据科学实战</title> <author>李四</author> </book> </library>
用 ElementTree 解析它:
立即学习“Python免费学习笔记(深入)”;
import xml.etree.ElementTree as ET <p>tree = ET.parse('books.xml') root = tree.getroot() # 获取根元素 <library>
遍历元素与访问数据
根对象是一个 Element,支持遍历子元素,并可通过属性或文本获取内容。
遍历所有 book 元素并打印信息:
for book in root.findall('book'): book_id = book.get('id') # 获取属性 title = book.find('title').text # 获取子元素文本 author = book.find('author').text print(f"ID: {book_id}, 书名: {title}, 作者: {author}")
输出:
ID: 1, 书名: Python入门, 作者: 张三 ID: 2, 书名: 数据科学实战, 作者: 李四
查找元素的常用方法
ElementTree 提供了灵活的查找方式:
-
find(match):返回第一个匹配的子元素 -
findall(match):返回所有匹配的子元素列表 -
get(Attribute):获取元素的属性值 -
.text:获取元素的文本内容
例如,查找所有作者为“李四”的书:
for book in root.findall("book[author='李四']"): print(book.find('title').text)
构建和写入XML
可以使用 ET.Element() 和 ET.SubElement() 创建 XML 结构。
root = ET.Element("library") book = ET.SubElement(root, "book", id="3") title = ET.SubElement(book, "title") title.text = "机器学习基础" author = ET.SubElement(book, "author") author.text = "王五" <h1>写入文件</h1><p>tree = ET.ElementTree(root) tree.write("new_books.xml", encoding="utf-8", xml_declaration=True)
生成的 XML 将包含声明和中文编码支持。
基本上就这些。ElementTree 简洁实用,适合大多数中小型 XML 处理任务。掌握 parse、find、get 和 text 这几个核心操作,就能快速上手处理日常 XML 数据。


