xml.dom篇
DOM是Document Object Model的簡(jiǎn)稱,XML 文檔的高級(jí)樹型表示。該模型并非只針對(duì) Python,而是一種普通XML 模型。Python 的 DOM 包是基于 SAX 構(gòu)建的,并且包括在 Python 2.0 的標(biāo)準(zhǔn) XML 支持里。
一、xml.dom的簡(jiǎn)單介紹
1、主要方法:
minidom.parse(filename):加載讀取XML文件
doc.documentElement:獲取XML文檔對(duì)象
node.getAttribute(AttributeName):獲取XML節(jié)點(diǎn)屬性值
node.getElementsByTagName(TagName):獲取XML節(jié)點(diǎn)對(duì)象集合
node.childNodes :返回子節(jié)點(diǎn)列表。
node.childNodes[index].nodeValue:獲取XML節(jié)點(diǎn)值
node.firstChild:訪問第一個(gè)節(jié)點(diǎn),等價(jià)于pagexml.childNodes[0]
返回Node節(jié)點(diǎn)的xml表示的文本:
doc = minidom.parse(filename)
doc.toxml('UTF-8')
訪問元素屬性:
Node.attributes["id"]
a.name #就是上面的 "id"
a.value #屬性的值
2、舉例說明
例1:文件名:book.xml
代碼如下:
<?xml version="1.0" encoding="utf-8"?>
<info>
<intro>Book message</intro>
<list id='001'>
<head>bookone</head>
<name>python check</name>
<number>001</number>
<page>200</page>
</list>
<list id='002'>
<head>booktwo</head>
<name>python learn</name>
<number>002</number>
<page>300</page>
</list>
</info>
(1)創(chuàng)建DOM對(duì)象
代碼如下:
import xml.dom.minidom
dom1=xml.dom.minidom.parse('book.xml')
(2)獲取根字節(jié)
root=dom1.documentElement #這里得到的是根節(jié)點(diǎn)
print root.nodeName,',',root.nodeValue,',',root.nodeType
返回結(jié)果為:
info , None , 1
其中:
info是指根節(jié)點(diǎn)的名稱root.nodeName
None是指根節(jié)點(diǎn)的值root.nodeValue
1是指根節(jié)點(diǎn)的類型root.nodeType,更多節(jié)點(diǎn)類型如下表: