实现说明
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)