← 中文资源

简体中文版本

ElementTree 构建并序列化 XML

用 Element 与 SubElement 从零搭出 XML 文档,tostring 序列化、indent 排版缩进,再经 fromstring 解析回来用路径查找读值,全程只用标准库,不需要外部 XML 库。

阅读英文原文

实现说明

feed、item、root、title 定义在模块顶层,中间不经过函数作用域。

使用要点

  • xml 必须先装好——示例直接导入它们。

常见问题

有第三方依赖吗?

xml——运行前用包管理器装上。

代码示例

import xml.etree.ElementTree as ET

# Build the document from Elements: attributes go in the constructor,
# nested content through SubElement
feed = ET.Element('feed', version='1.0')
item = ET.SubElement(feed, 'item', id='42')
ET.SubElement(item, 'title').text = 'Cache warm-up finished'
ET.SubElement(item, 'duration', unit='s').text = '18'

# encoding='unicode' returns a str; 'utf-8' would return bytes
print(ET.tostring(feed, encoding='unicode'))

# indent() adds whitespace so the serialized tree reads clearly
ET.indent(feed, space='  ')
print(ET.tostring(feed, encoding='unicode'))

# Round trip through fromstring and read with path lookups
root = ET.fromstring(ET.tostring(feed))
title = root.find('item/title').text
unit = root.find('item/duration').attrib['unit']
print(title, unit)