使用 xml.etree 解析 Python XML | AI生成和翻译

Home 2025.08

Python 中的 xml.etree 概述

xml.etree 是 Python 内置模块(特指 xml.etree.ElementTree),用于解析和操作 XML 数据。它提供树状结构,可以高效地读取、写入、修改和遍历 XML 元素。该模块轻量级且无需外部库,非常适合基础 XML 处理任务。通过 import xml.etree.ElementTree as ET 导入使用。

解析 XML

通过以下方式将 XML 加载到内存中:

import xml.etree.ElementTree as ET

# 从字符串解析
xml_data = "<root><child>text</child></root>"
root = ET.fromstring(xml_data)

# 从文件解析
tree = ET.parse('example.xml')
root = tree.getroot()

遍历元素

解析后可遍历 XML 树:

# 示例 XML: <bookstore><book id="1"><title>Python</title></book></bookstore>
for book in root.findall('book'):
    title = book.find('title').text
    book_id = book.attrib['id']
    print(f"图书 {book_id}: {title}")

修改 XML

动态编辑元素:

new_child = ET.SubElement(root, 'new_element')
new_child.text = '新增内容'
new_child.set('attr', '值')

写入 XML

将修改保存回 XML:

xml_output = ET.tostring(root, encoding='unicode')
with open('output.xml', 'w') as f:
    f.write(xml_output)

# 或直接写入
tree.write('output.xml')

完整示例

以下为解析、修改和写入 XML 的完整脚本:

import xml.etree.ElementTree as ET

# 输入 XML 字符串
xml_str = """<library>
  <book id="1"><title>1984</title><author>Orwell</author></book>
</library>"""

root = ET.fromstring(xml_str)

# 添加新图书
new_book = ET.SubElement(root, 'book', id="2")
ET.SubElement(new_book, 'title').text = 'Brave New World'
ET.SubElement(new_book, 'author').text = 'Huxley'

# 打印所有图书
for book in root:
    title = book.find('title').text
    author = book.find('author').text
    print(f"{title} 作者:{author}")

# 写入文件
ET.tostring(root, encoding='unicode')
# 或 root.write('library.xml')

注意事项


Back

x-ai/grok-code-fast-1

Donate