使用Python中的DOM API解析XML

文档对象模型(“ 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
# 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