DOM 解析器介紹
DOM的 xml.dom.minidom 子模塊、xml.dom.pulldom 子模塊分別提供兩種形式的解析器。
- xml.dom.minidom 子模塊
主要提供對 XML 文檔的讀、修改操作,解析器的使用格式如下:
xml.dom.minidom.parse(filename_or_file,parse=None,bufsize=None)
該解析器解析成功,返回指定 XML 文件的一個文檔對象。
本文用到的 DOM 對象的相關函數介紹
1.1 Node 接口對象相關函數
Node.childNodes,返回當前節點中包含的節點列表,這是一個只讀屬性。
1.2 Document 接口對象相關函數
Document.documentElement,返回文檔的所有元素。
Document.getElementsByTagName(tagName),搜索所有具有特定元素類型名稱下的子元素,返回元素集合。
1.3 Element 接口對象相關函數
Element.hasAttribute(name),如果元素具有按指定 name 命名的屬性,返回True。
Element.getAttribute(name),以字符串形式返回指定 name 命名的屬性的值,如果不存在這樣的標簽,則返回空字符串。
Element.setAttribute(name,value),設置 name 標簽指定的值。
Element.removeAttribute(name),刪除 name 標簽指定的元素。
文件解析示例
1、 XML文件(movies.xml)
<collection shelf="New Arrivals">
<movies title="Enemy Behind">
<type>War, Thriller</type>
<format>DVD</format>
<year>2003</year>
<rating>PG</rating>
<stars>10</stars>
<description>Talk about a US-Japan war</description>
</movies>
</collection>
2、 DOM解析XML文件(sax_movie.py)
from xml.dom.minidom import parse
import xml.dom.minidom
# 使用minidom解析器打開 XML 文檔
DOMTree = xml.dom.minidom.parse('D:\\My-python\\XML\\movies.xml')
# 該解析器解析成功,返回一個文檔對象DOMTree接收
collection = DOMTree.documentElement # 把所有的元素存入集合中
print(collection.toxml())
if collection.hasAttribute("shelf"):
print ("Root element : %s" % collection.getAttribute("shelf"))
# 獲取movie元素下的子元素集合
movies = collection.getElementsByTagName("movies")
movies_record = []
# 打印每部電影的詳細信息
for movie in movies:
if movie.hasAttribute("title"): # 判斷是否存在title屬性
movies_record.append(movie.getAttribute("title")) # 獲取屬性對應的值
type = movie.getElementsByTagName('type')[0] # 獲取 type 標簽對應的元素
movies_record.append(type.childNodes[0].data) # 獲取 type 元素對應的值
format = movie.getElementsByTagName('format')[0]
movies_record.append(format.childNodes[0].data)
rating = movie.getElementsByTagName('rating')[0]
movies_record.append(rating.childNodes[0].data)
stars = movie.getElementsByTagName('stars')[0]
movies_record.append(stars.childNodes[0].data)
description = movie.getElementsByTagName('description')[0]
movies_record.append(description.childNodes[0].data)
print(movies_record)
3、 運行結果
<collection shelf="New Arrivals">
<movies title="Enemy Behind">
<type>War, Thriller</type>
<format>DVD</format>
<year>2003</year>
<rating>PG</rating>
<stars>10</stars>
<description>Talk about a US-Japan war</description>
</movies>
</collection>
Root element : New Arrivals
['Enemy Behind', 'War, Thriller', 'DVD', 'PG', '10', 'Talk about a US-Japan war']
DOM實現對XML文件內容的修改
1、 代碼(DOM_edit_XML.py)
from xml.dom.minidom import parse
import xml.dom.minidom
# 使用minidom解析器打開 XML 文檔
DOMTree = xml.dom.minidom.parse('D:\\My-python\\XML\\movies.xml')
# 該解析器解析成功,返回一個文檔對象DOMTree接收
# 把所有的元素存入集合中
collection = DOMTree.documentElement
# 獲取 stars 的 NodeList 對象集合
stars = collection.getElementsByTagName("stars")
stars_object = stars[0] # 獲取列表第一個price節點(元素)
stars_object.firstChild.data = 12 # 修改第一個節點的值
print('修改數量成功!')
# 獲取 movies 的 NodeList 對象集合
movies = collection.getElementsByTagName("movies")
collection.removeChild(movies[1])
print('刪除節點成功')
f = open('D:\\My-python\\XML\\movies.xml','w',encoding='utf-8')
f.write(DOMTree.toxml())
f.close()
2、 修改結果
<?xml version="1.0" ?>
<collection shelf="New Arrivals">
<movies title="Enemy Behind">
<type>War, Thriller</type>
<format>DVD</format>
<year>2003</year>
<rating>PG</rating>
<stars>12</stars>
<description>Talk about a US-Japan war</description>
</movies>
</collection>

