在 Python 中使用 DOM API 分析 XML


文件物件模型(“DOM”)是全球資訊網聯盟(W3C)釋出的一種跨語言 API,用於訪問和修改 XML 文件。

DOM 特別適用於隨機訪問應用程式。SAX 一次只允許您檢視文件的一部分。如果您正在檢視一個 SAX 元素,您將無法訪問其他元素。

以下是快速載入 XML 文件並使用 xml.dom 模組建立 minidom 物件的最簡單方法。minidom 物件提供了一個簡單的解析器方法來根據 XML 檔案迅速建立 DOM 樹。

示例語句呼叫 minidom 物件的 parse( file [, parser] ) 函式來解析由 file 指定的 XML 檔案,並將其解析為 DOM 樹物件。

#!/usr/bin/python
from xml.dom.minidom import parse
import xml.dom.minidom
# Open XML document using minidom parser
DOMTree = xml.dom.minidom.parse("movies.xml")
collection = DOMTree.documentElement
if collection.hasAttribute("shelf"):
   print "Root element : %s" % collection.getAttribute("shelf")
# Get all the movies in the collection
movies = collection.getElementsByTagName("movie")
# Print detail of each movie.
for movie in movies:
print "*****Movie*****"
   if movie.hasAttribute("title"):
      print "Title: %s" % movie.getAttribute("title")
   type = movie.getElementsByTagName('type')[0]
   print "Type: %s" % type.childNodes[0].data
   format = movie.getElementsByTagName('format')[0]
   print "Format: %s" % format.childNodes[0].data
   rating = movie.getElementsByTagName('rating')[0]
   print "Rating: %s" % rating.childNodes[0].data
   description = movie.getElementsByTagName('description')[0]
   print "Description: %s" % description.childNodes[0].data

這將產生以下結果 −

Root element : New Arrivals
*****Movie*****
Title: Enemy Behind
Type: War, Thriller
Format: DVD
Rating: PG
Description: Talk about a US-Japan war
*****Movie*****
Title: Transformers
Type: Anime, Science Fiction
Format: DVD
Rating: R
Description: A schientific fiction
*****Movie*****
Title: Trigun
Type: Anime, Action
Format: DVD
Rating: PG
Description: Vash the Stampede!
*****Movie*****
Title: Ishtar
Type: Comedy
Format: VHS
Rating: PG
Description: Viewable boredom

有關 DOM API 文件的完整詳細資訊,請參閱標準 Python API

更新時間:31-Jan-2020

2K+ 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.