Python解析XML用ElementTree吗

wen python案例 5

是的,xml.etree.ElementTree 是 Python 标准库中最常用、最推荐的解析 XML 的模块,它在处理中等规模 XML 文件时非常高效,且无需安装第三方库。

Python解析XML用ElementTree吗

核心特点:

  • 轻量级,内置于 Python 标准库
  • 支持解析和创建 XML 文档
  • 提供两种解析方式:DOM 式和流式

基本使用示例:

import xml.etree.ElementTree as ET
# 解析 XML 字符串或文件
xml_data = '''
<bookstore>
    <book category="fiction">
        <title>Python入门</title>
        <author>张三</author>
        <price>39.90</price>
    </book>
    <book category="non-fiction">
        <title>数据结构</title>
        <author>李四</author>
        <price>45.00</price>
    </book>
</bookstore>
'''
# 方法1:解析字符串
root = ET.fromstring(xml_data)
# 方法2:解析文件(推荐)
# tree = ET.parse('books.xml')
# root = tree.getroot()
# 遍历所有book元素
for book in root.findall('book'):= book.find('title').text
    author = book.find('author').text
    price = book.find('price').text
    category = book.get('category')
    print(f"《{title}》 - {author} - ¥{price} - {category}")

其他常见操作:

# 查找特定元素s = root.findall('.//title')  # XPath 支持
first_book = root.find('book')
last_book = root.findall('book')[-1]
# 修改XML
for price in root.iter('price'):
    price.text = str(float(price.text) * 0.9)  # 打9折
# 保存修改
# tree.write('books_updated.xml', encoding='utf-8', xml_declaration=True)

何时选择其他库:

  • lxml:当需要更强大的 XPath 支持、XSLT 转换或处理超大文件时(非标准库,需安装)
  • minidom:当需要完整的 DOM 操作风格时(标准库,但比 ElementTree 笨重)
  • SAX:当处理超大文件且内存敏感时(流式解析,标准库)

对于 90% 的 XML 解析任务,ElementTree 都是最佳选择。

抱歉,评论功能暂时关闭!