xml.etree.ElementTree(及加速版 cElementTree)是 Python 標準庫中最輕量、API 最友善的 XML 處理工具,兼具 DOM 易用性與 SAX 低記憶體優勢。本文系統整理 XML 基礎概念、三大解析策略比較,並以完整範例示範 ElementTree 核心操作。
<foo>...</foo> 或 <foo/><foo lang="EN">,各元素獨立屬性集xmlns="URI" 或 xmlns:prefix="URI"| 策略 | 原理 | 優點 | 缺點 |
|---|---|---|---|
| SAX | 事件驅動、流式讀取 | 快、省記憶體 | 需自寫回調、無法隨機存取 |
| DOM | 整份文件建樹於記憶體 | 隨機存取、結構完整 | 慢、佔記憶體、API 繁瑣 |
| ElementTree | 輕量級樹模型、友善 API | 快、省記憶體、代碼簡潔 | 極大檔案仍需串流處理 |
try:
import xml.etree.cElementTree as ET # C 加速版
except ImportError:
import xml.etree.ElementTree as ET # 純 Python 回退
ET.parse('file.xml'):載入檔案回傳 ElementTree 物件ET.fromstring(xml_text):從字串解析root.findall('tag') / find() / getiterator():節點查找elem.attrib:屬性字典elem.text:節點文本elem.tag:標籤名
Book message
bookone
python check
001
200
booktwo
python learn
002
300
# coding=utf-8
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
root = ET.parse('book.xml')
books = root.findall('./list') # 所有 list 子節點
for book_list in books:
print("=" * 30)
for book in book_list:
if 'id' in book.attrib:
print("id:", book.attrib['id'])
print(f"{book.tag}=> {book.text}")
print("=" * 30)
==============================
head=> bookone
name=> python check
number=> 001
page=> 200
==============================
head=> booktwo
name=> python learn
number=> 002
page=> 300
==============================
iter() 進行深度優先遍歷XPath 風格路徑:findall('.//list/name')ET.ElementTree(root).write('out.xml', encoding='utf-8'){URI} 或建立 prefix map