Python使用xml.dom解析xml

时间:2023-03-08 23:01:31
Python使用xml.dom解析xml

在菜鸟教程上找了个关于电影信息的xml类型的文档,用python内置的xml.dom来解析提取一下信息。

先复习一下xml概念:

  • XML 指可扩展标记语言(EXtensible Markup Language)
  • XML 是一种标记语言,很类似 HTML
  • XML 的设计宗旨是传输数据,而非显示数据
  • XML 被设计为具有自我描述性。
  • XML 是 W3C 的推荐标准

解析工具:

文件对象模型(Document Object Model,简称DOM),是W3C组织推荐的处理可扩展置标语言的标准编程接口。

解析原理:一个 DOM 的解析器在解析一个 XML 文档时,一次性读取整个文档,把文档中所有元素保存在内存中的一个树结构里,之后可以利用DOM 提供的不同的函数来读取或修改文档的内容和结构,也可以把修改过的内容写入xml文件。

XML代码如下

目录层次:

collect shelf

movie title

xxxx

xxxx

Python使用xml.dom解析xml

Python解析代码

from xml.dom.minidom import parse
import xml.dom.minidom #使用Minidom解析器打开xml文档
DOMTree = xml.dom.minidom.parse("mov.xml")
collection = DOMTree.documentElement
if collection.hasAttribute("shelf"):
print("Root element : %s " % collection.getAttribute("shelf")) #self.getElementsByTagName("xx")取下级
#在集合里面获取所有电影
movies = collection.getElementsByTagName("movie") #打印每部电影的详细信息
for movie in movies:
print("********movies*********")
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) #有些电影里不一定有year这条信息,用if语句不会导致报错
if movie.getElementsByTagName("year"):
year = movie.getElementsByTagName("year")[0]
print("year : %s" % year.childNodes[0].data) if movie.getElementsByTagName("episodes"):
episodes = movie.getElementsByTagName("episodes")[0]
print("episodes : %s" % episodes.childNodes[0].data) rating = movie.getElementsByTagName("rating")[0]
print("rating : %s" % rating.childNodes[0].data) stars = movie.getElementsByTagName("stars")[0]
print("stars : %s" % stars.childNodes[0].data) description = movie.getElementsByTagName("description")[0]
print("description : %s" % description.childNodes[0].data)

输出结果:

Root element : New Arrivals
********movies*********
title : Enemy Behind
type : War, Thriller
Format : DVD
year : 2003
rating : PG
stars : 10
description : Talk about a US-Japan war
********movies*********
title : Transformers
type : Anime, Science Fiction
Format : DVD
year : 1989
rating : R
stars : 8
description : A schientific fiction
********movies*********
title : Trigun
type : Anime, Action
Format : DVD
episodes : 4
rating : PG
stars : 10
description : Vash the Stampede!
********movies*********
title : Ishtar
type : Comedy
Format : VHS
rating : PG
stars : 2
description : Viewable boredom