使用DOM解析xml(python3.4)

一、DOM(Document Object Model)

将XML数据在内存中解析成一个树,通过对树的操作来操作XML。

二、

XML实例文件movies.xml:

<collection shelf="New Arrivals">
<movie title="Enemy Behind">    <!-- 属性(attribute) -->
   <type>War, Thriller</type>    <!-- 元素(element) --> 
   <format>DVD</format>
   <year>2003</year>
   <rating>PG</rating>
   <stars>10</stars>
   <description>Talk about a US-Japan war</description>
</movie>
<movie title="Transformers">
   <type>Anime, Science Fiction</type>
   <format>DVD</format>
   <year>1989</year>
   <rating>R</rating>
   <stars>8</stars>
   <description>A schientific fiction</description>
</movie>
</collection>

解析代码:

from xml.dom.minidom import parse
import xml.dom.minidom

# 使用minidom解析器打开 XML 文档
DOMTree = xml.dom.minidom.parse("e:/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]  # [0]:若存在同名的,用以区分
   print ("Type: %s" % type.childNodes[0].data)  # type.childNodes[0]表示type标签下的第一个内容或者子标签
   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)

childNodes -----> 嵌套列表???

三、常用方法:

minidom.parse(filename)    #加载读取XML文件
 
doc.documentElement        #获取XML文档对象
 
node.getAttribute(AttributeName)    #获取XML节点属性值
 
node.getElementsByTagName(TagName)    #获取XML节点对象集合
 
node.childNodes    #返回子节点列表。
 
node.childNodes[index].nodeValue    #获取XML节点值
 
node.firstChild    #访问第一个节点。等价于pagexml.childNodes[0]
 
doc = minidom.parse(filename)
doc.toxml('UTF-8')    #返回Node节点的xml表示的文本
 
Node.attributes["id"]    #访问元素属性
a.name    #就是上面的 "id"
a.value    #属性的值

http://www.cnblogs.com/kaituorensheng/p/4493306.html

原文地址:https://www.cnblogs.com/stellar/p/5980590.html