使用 Python 中的 DOM API 解析 XML

pythonserver side programmingprogramming更新于 2025/5/11 2:20:17

文档对象模型 ("DOM") 是万维网联盟 (W3C) 提供的跨语言 API,用于访问和修改 XML 文档。

DOM 对于随机访问应用程序非常有用。SAX 只允许您一次查看文档的一部分。如果您正在查看一个 SAX 元素,则无法访问另一个元素。

这是使用 xml.dom 模块快速加载 XML 文档和创建 minidom 对象的最简单方法。 minidom 对象提供了一个简单的解析器方法,可以从 XML 文件快速创建 DOM 树。

示例语句调用 minidom 对象的 parse(file[,parser]) 函数将 file 指定的 XML 文件解析为 DOM 树对象。

#!/usr/bin/python
from xml.dom.minidom import parse
import xml.dom.minidom
# 使用 minidom 解析器打开 XML 文档
DOMTree = xml.dom.minidom.parse("movies.xml")
collection = DOMTree.documentElement
if collection.hasAttribute("shelf"):
   print "Root element : %s" % collection.getAttribute("shelf")
# 获取集合中的所有电影
movies = collection.getElementsByTagName("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。


相关文章


有用资源