python XML解析

什么是XML?

XML 指可擴(kuò)展標(biāo)記語(yǔ)言(eXtensible Markup Language)。 你可以通過(guò)本站學(xué)習(xí)XML教程

XML 被設(shè)計(jì)用來(lái)傳輸和存儲(chǔ)數(shù)據(jù)。

XML是一套定義語(yǔ)義標(biāo)記的規(guī)則,這些標(biāo)記將文檔分成許多部件并對(duì)這些部件加以標(biāo)識(shí)。

它也是元標(biāo)記語(yǔ)言,即定義了用于定義其他與特定領(lǐng)域有關(guān)的、語(yǔ)義的、結(jié)構(gòu)化的標(biāo)記語(yǔ)言的句法語(yǔ)言。


python對(duì)XML的解析

常見(jiàn)的XML編程接口有DOM和SAX,這兩種接口處理XML文件的方式不同,當(dāng)然使用場(chǎng)合也不同。

python有三種方法解析XML,SAX,DOM,以及ElementTree:

1.SAX (simple API for XML )

python 標(biāo)準(zhǔn)庫(kù)包含SAX解析器,SAX用事件驅(qū)動(dòng)模型,通過(guò)在解析XML的過(guò)程中觸發(fā)一個(gè)個(gè)的事件并調(diào)用用戶定義的回調(diào)函數(shù)來(lái)處理XML文件。

2.DOM(Document Object Model)

將XML數(shù)據(jù)在內(nèi)存中解析成一個(gè)樹(shù),通過(guò)對(duì)樹(shù)的操作來(lái)操作XML。

3.ElementTree(元素樹(shù))

ElementTree就像一個(gè)輕量級(jí)的DOM,具有方便友好的API。代碼可用性好,速度快,消耗內(nèi)存少。

注:因DOM需要將XML數(shù)據(jù)映射到內(nèi)存中的樹(shù),一是比較慢,二是比較耗內(nèi)存,而SAX流式讀取XML文件,比較快,占用內(nèi)存少,但需要用戶實(shí)現(xiàn)回調(diào)函數(shù)(handler)。

本章節(jié)使用到的XML實(shí)例文件movies.xml內(nèi)容如下:

<pre class="prettyprint prettyprinted" style="color: rgb(0, 0, 0); font-family: "Courier New"; font-size: 12px; margin: 5px 8px; padding: 5px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"><collection shelf="New Arrivals"> <movie 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> </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> <movie title="Trigun"> <type>Anime, Action</type> <format>DVD</format> <episodes>4</episodes> <rating>PG</rating> <stars>10</stars> <description>Vash the Stampede!</description> </movie> <movie title="Ishtar"> <type>Comedy</type> <format>VHS</format> <rating>PG</rating> <stars>2</stars> <description>Viewable boredom</description> </movie> </collection></pre>


python使用SAX解析xml

SAX是一種基于事件驅(qū)動(dòng)的API。

利用SAX解析XML文檔牽涉到兩個(gè)部分:解析器和事件處理器。

解析器負(fù)責(zé)讀取XML文檔,并向事件處理器發(fā)送事件,如元素開(kāi)始跟元素結(jié)束事件;

而事件處理器則負(fù)責(zé)對(duì)事件作出相應(yīng),對(duì)傳遞的XML數(shù)據(jù)進(jìn)行處理。

<psax適于處理下面的問(wèn)題:< p="">

  • 1、對(duì)大型文件進(jìn)行處理;
  • 2、只需要文件的部分內(nèi)容,或者只需從文件中得到特定信息。
  • 3、想建立自己的對(duì)象模型的時(shí)候。

在python中使用sax方式處理xml要先引入xml.sax中的parse函數(shù),還有xml.sax.handler中的ContentHandler。

ContentHandler類(lèi)方法介紹

characters(content)方法

調(diào)用時(shí)機(jī):

從行開(kāi)始,遇到標(biāo)簽之前,存在字符,content的值為這些字符串。

從一個(gè)標(biāo)簽,遇到下一個(gè)標(biāo)簽之前, 存在字符,content的值為這些字符串。

從一個(gè)標(biāo)簽,遇到行結(jié)束符之前,存在字符,content的值為這些字符串。

標(biāo)簽可以是開(kāi)始標(biāo)簽,也可以是結(jié)束標(biāo)簽。

startDocument()方法

文檔啟動(dòng)的時(shí)候調(diào)用。

endDocument()方法

解析器到達(dá)文檔結(jié)尾時(shí)調(diào)用。

startElement(name, attrs)方法

遇到XML開(kāi)始標(biāo)簽時(shí)調(diào)用,name是標(biāo)簽的名字,attrs是標(biāo)簽的屬性值字典。

endElement(name)方法

遇到XML結(jié)束標(biāo)簽時(shí)調(diào)用。


make_parser方法

以下方法創(chuàng)建一個(gè)新的解析器對(duì)象并返回。

<pre class="prettyprint prettyprinted" style="color: rgb(0, 0, 0); font-family: "Courier New"; font-size: 12px; margin: 5px 8px; padding: 5px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">xml.sax.make_parser( [parser_list] )</pre>

參數(shù)說(shuō)明:

  • parser_list - 可選參數(shù),解析器列表

parser方法

以下方法創(chuàng)建一個(gè) SAX 解析器并解析xml文檔:

<pre class="prettyprint prettyprinted" style="color: rgb(0, 0, 0); font-family: "Courier New"; font-size: 12px; margin: 5px 8px; padding: 5px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">xml.sax.parse( xmlfile, contenthandler[, errorhandler])</pre>

參數(shù)說(shuō)明:

  • xmlfile - xml文件名
  • contenthandler - 必須是一個(gè)ContentHandler的對(duì)象
  • errorhandler - 如果指定該參數(shù),errorhandler必須是一個(gè)SAX ErrorHandler對(duì)象

parseString方法

parseString方法創(chuàng)建一個(gè)XML解析器并解析xml字符串:

<pre class="prettyprint prettyprinted" style="color: rgb(0, 0, 0); font-family: "Courier New"; font-size: 12px; margin: 5px 8px; padding: 5px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">xml.sax.parseString(xmlstring, contenthandler[, errorhandler])</pre>

參數(shù)說(shuō)明:

  • xmlstring - xml字符串
  • contenthandler - 必須是一個(gè)ContentHandler的對(duì)象
  • errorhandler - 如果指定該參數(shù),errorhandler必須是一個(gè)SAX ErrorHandler對(duì)象

Python 解析XML實(shí)例

<pre class="prettyprint prettyprinted" style="color: rgb(0, 0, 0); font-family: "Courier New"; font-size: 12px; margin: 5px 8px; padding: 5px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">#!/usr/bin/python # -- coding: UTF-8 -- import xml.sax

class MovieHandler( xml.sax.ContentHandler ): def init(self): self.CurrentData = "" self.type = "" self.format = "" self.year = "" self.rating = "" self.stars = "" self.description = "" # 元素開(kāi)始事件處理 def startElement(self, tag, attributes): self.CurrentData = tag
if tag == "movie": print "*****Movie*****" title = attributes["title"] print "Title:", title

元素結(jié)束事件處理 def endElement(self, tag): if self.CurrentData == "type": print "Type:", self.type

  elif self.CurrentData == "format": print "Format:", self.format
  elif self.CurrentData == "year": print "Year:", self.year
  elif self.CurrentData == "rating": print "Rating:", self.rating
  elif self.CurrentData == "stars": print "Stars:", self.stars
  elif self.CurrentData == "description": print "Description:", self.description
  self.CurrentData = "" # 內(nèi)容事件處理 def characters(self, content): if self.CurrentData == "type": self.type = content
  elif self.CurrentData == "format": self.format = content
  elif self.CurrentData == "year": self.year = content
  elif self.CurrentData == "rating": self.rating = content
  elif self.CurrentData == "stars": self.stars = content
  elif self.CurrentData == "description": self.description = content

if ( name == "main"): # 創(chuàng)建一個(gè) XMLReader parser = xml.sax.make_parser() # turn off namepsaces parser.setFeature(xml.sax.handler.feature_namespaces, 0) # 重寫(xiě) ContextHandler Handler = MovieHandler() parser.setContentHandler( Handler ) parser.parse("movies.xml")</pre>

以上代碼執(zhí)行結(jié)果如下:

<pre class="prettyprint prettyprinted" style="color: rgb(0, 0, 0); font-family: "Courier New"; font-size: 12px; margin: 5px 8px; padding: 5px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">*****Movie***** Title: Enemy Behind Type: War, Thriller Format: DVD
Year: 2003 Rating: PG
Stars: 10 Description: Talk about a US-Japan war
*****Movie***** Title: Transformers Type: Anime, Science Fiction Format: DVD
Year: 1989 Rating: R
Stars: 8 Description: A schientific fiction
*****Movie***** Title: Trigun Type: Anime, Action Format: DVD
Rating: PG
Stars: 10 Description: Vash the Stampede! *****Movie***** Title: Ishtar Type: Comedy Format: VHS
Rating: PG
Stars: 2 Description: Viewable boredom</pre>

完整的 SAX API 文檔請(qǐng)查閱Python SAX APIs


使用xml.dom解析xml

文件對(duì)象模型(Document Object Model,簡(jiǎn)稱DOM),是W3C組織推薦的處理可擴(kuò)展置標(biāo)語(yǔ)言的標(biāo)準(zhǔn)編程接口。

一個(gè) DOM 的解析器在解析一個(gè) XML 文檔時(shí),一次性讀取整個(gè)文檔,把文檔中所有元素保存在內(nèi)存中的一個(gè)樹(shù)結(jié)構(gòu)里,之后你可以利用DOM 提供的不同的函數(shù)來(lái)讀取或修改文檔的內(nèi)容和結(jié)構(gòu),也可以把修改過(guò)的內(nèi)容寫(xiě)入xml文件。

python中用xml.dom.minidom來(lái)解析xml文件,實(shí)例如下:

<pre class="prettyprint prettyprinted" style="color: rgb(0, 0, 0); font-family: "Courier New"; font-size: 12px; margin: 5px 8px; padding: 5px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">#!/usr/bin/python # -- coding: UTF-8 -- from xml.dom.minidom import parse
import xml.dom.minidom

使用minidom解析器打開(kāi) XML 文檔 DOMTree = xml.dom.minidom.parse("movies.xml") collection = DOMTree.documentElement

if collection.hasAttribute("shelf"): print "Root element : %s" % collection.getAttribute("shelf") # 在集合中獲取所有電影 movies = collection.getElementsByTagName("movie") # 打印每部電影的詳細(xì)信息 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</pre>

以上程序執(zhí)行結(jié)果如下:

<pre class="prettyprint prettyprinted" style="color: rgb(0, 0, 0); font-family: "Courier New"; font-size: 12px; margin: 5px 8px; padding: 5px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">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</pre>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
禁止轉(zhuǎn)載,如需轉(zhuǎn)載請(qǐng)通過(guò)簡(jiǎn)信或評(píng)論聯(lián)系作者。

相關(guān)閱讀更多精彩內(nèi)容

  • Python XML解析 作者:楊夢(mèng)鴿 校對(duì):翟舒青 什么是XML? XML 指可擴(kuò)展標(biāo)記語(yǔ)言(eXtensibl...
    木易林1閱讀 877評(píng)論 1 4
  • 第一組:楊昊 今天給大家分享一部網(wǎng)絡(luò)神?。骸睹_》。 是的沒(méi)錯(cuò),就是這么清新脫俗的名字,而且可能畫(huà)質(zhì)不好(劇組沒(méi)錢(qián)...
    胡諾閱讀 594評(píng)論 0 1
  • 1.SAX模塊 SAX是一種基于事件驅(qū)動(dòng)的API,利用SAX解析XML牽扯到兩個(gè)部分,解析器和事件處理器。其中解析...
    MoonMonsterss閱讀 2,372評(píng)論 0 0
  • python用來(lái)操作XML格式文檔有兩種方式,一種是DOM方式,將文檔讀取到內(nèi)存中操作,然后導(dǎo)出到磁盤(pán)中,優(yōu)點(diǎn)是操...
    MoonMonsterss閱讀 6,231評(píng)論 0 1
  • 侵襲性真菌感染(IFI): 指致病性真菌侵犯皮下組織、黏膜、肌肉和內(nèi)臟器官等所引起的真菌感染性疾病,危害性較大。常...
    Allex閱讀 2,139評(píng)論 0 1

友情鏈接更多精彩內(nèi)容