Python 內建 xml.dom.minidom 提供 DOM 風格 XML 解析,本文以書籍目錄為例,示範節點遍歷、元素提取、缺失標籤防禦性檢查等實務技巧。
<?xml version="1.0" encoding="utf-8"?>
<books>
<book>
<author>zoer</author>
<title>think in java</title>
<content>this is a good book</content>
</book>
<book>
<author>naughty</author>
<title>gone with the wind</title>
<content>this is a good book 2</content>
</book>
<book>
<author>cc</author>
<content>this is a good book 3</content>
</book>
</books>
注意:第三本書缺少 <title> 標籤,實務中極常見。
#coding=utf-8
import xml.dom.minidom
dom = xml.dom.minidom.parse('books.xml')
root = dom.documentElement
for node in root.childNodes:
if node.nodeType == node.ELEMENT_NODE: # 過濾文字節點
# 安全提取 author
author = node.getElementsByTagName("author")
if len(author) >= 1:
print(author[0].childNodes[0].data)
# 安全提取 title (可能缺失)
title = node.getElementsByTagName("title")
if len(title) >= 1:
print(title[0].childNodes[0].data)
# 安全提取 content
content = node.getElementsByTagName("content")
if len(content) >= 1:
print(content[0].childNodes[0].data)
print("........................parting line........................")
node.nodeType == node.ELEMENT_NODE:過濾換行、縮排產生的文字節點。getElementsByTagName 回傳列表:必須檢查長度再存取 [0],避免 IndexError。childNodes[0].data:取得文字節點實際內容。#coding=utf-8 確保中文輸出正常。現代專案建議考慮 lxml.etree(效能更好、支援 XPath)或 xml.etree.ElementTree(標準庫、API 更 Pythonic)。但 minidom 無額外依賴,適合輕量腳本或受限環境。