Python 3 教程
XML 指可擴(kuò)展標(biāo)記語言(eXtensible Markup Language),標(biāo)準(zhǔn)通用標(biāo)記語言的子集,是一種用于標(biāo)記電子文件使其具有結(jié)構(gòu)性的標(biāo)記語言。 你可以通過本站學(xué)習(xí) XML 教程
XML 被設(shè)計(jì)用來傳輸和存儲(chǔ)數(shù)據(jù)。
XML 是一套定義語義標(biāo)記的規(guī)則,這些標(biāo)記將文檔分成許多部件并對(duì)這些部件加以標(biāo)識(shí)。
它也是元標(biāo)記語言,即定義了用于定義其他與特定領(lǐng)域有關(guān)的、語義的、結(jié)構(gòu)化的標(biāo)記語言的句法語言。
常見的 XML 編程接口有 DOM 和 SAX,這兩種接口處理 XML 文件的方式不同,當(dāng)然使用場(chǎng)合也不同。
Python 有三種方法解析 XML,SAX,DOM,以及 ElementTree:
Python 標(biāo)準(zhǔn)庫包含 SAX 解析器,SAX 用事件驅(qū)動(dòng)模型,通過在解析 XML 的過程中觸發(fā)一個(gè)個(gè)的事件并調(diào)用用戶定義的回調(diào)函數(shù)來處理 XML 文件。
將 XML 數(shù)據(jù)在內(nèi)存中解析成一個(gè)樹,通過對(duì)樹的操作來操作 XML。
本章節(jié)使用到的 XML 實(shí)例文件 movies.xml 內(nèi)容如下:
<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>
SAX 是一種基于事件驅(qū)動(dòng)的API。
利用 SAX 解析 XML 文檔牽涉到兩個(gè)部分: 解析器和事件處理器。
解析器負(fù)責(zé)讀取 XML 文檔,并向事件處理器發(fā)送事件,如元素開始跟元素結(jié)束事件。
而事件處理器則負(fù)責(zé)對(duì)事件作出響應(yīng),對(duì)傳遞的 XML 數(shù)據(jù)進(jìn)行處理。
在 Python 中使用 sax 方式處理 xml 要先引入 xml.sax 中的 parse 函數(shù),還有 xml.sax.handler 中的 ContentHandler。
characters(content) 方法
調(diào)用時(shí)機(jī):
從行開始,遇到標(biāo)簽之前,存在字符,content 的值為這些字符串。
從一個(gè)標(biāo)簽,遇到下一個(gè)標(biāo)簽之前, 存在字符,content 的值為這些字符串。
從一個(gè)標(biāo)簽,遇到行結(jié)束符之前,存在字符,content 的值為這些字符串。
標(biāo)簽可以是開始標(biāo)簽,也可以是結(jié)束標(biāo)簽。
startDocument() 方法
文檔啟動(dòng)的時(shí)候調(diào)用。
endDocument() 方法
解析器到達(dá)文檔結(jié)尾時(shí)調(diào)用。
startElement(name, attrs) 方法
遇到XML開始標(biāo)簽時(shí)調(diào)用,name 是標(biāo)簽的名字,attrs 是標(biāo)簽的屬性值字典。
endElement(name) 方法
遇到XML結(jié)束標(biāo)簽時(shí)調(diào)用。
以下方法創(chuàng)建一個(gè)新的解析器對(duì)象并返回。
xml.sax.make_parser( [parser_list] )
參數(shù)說明:
以下方法創(chuàng)建一個(gè) SAX 解析器并解析xml文檔:
xml.sax.parse( xmlfile, contenthandler[, errorhandler])
參數(shù)說明:
parseString 方法創(chuàng)建一個(gè) XML 解析器并解析 xml 字符串:
xml.sax.parseString(xmlstring, contenthandler[, errorhandler])
參數(shù)說明:
#!/usr/bin/python3 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 = "" # 元素開始調(diào)用 def startElement(self, tag, attributes): self.CurrentData = tag if tag == "movie": print ("*****Movie*****") title = attributes["title"] print ("Title:", title) # 元素結(jié)束調(diào)用 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 = "" # 讀取字符時(shí)調(diào)用 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() # 關(guān)閉命名空間 parser.setFeature(xml.sax.handler.feature_namespaces, 0) # 重寫 ContextHandler Handler = MovieHandler() parser.setContentHandler( Handler ) parser.parse("movies.xml")
以上代碼執(zhí)行結(jié)果如下:
*****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
完整的 SAX API 文檔請(qǐng)查閱Python SAX APIs
文件對(duì)象模型(Document Object Model,簡(jiǎn)稱DOM),是W3C組織推薦的處理可擴(kuò)展置標(biāo)語言的標(biāo)準(zhǔn)編程接口。
一個(gè) DOM 的解析器在解析一個(gè) XML 文檔時(shí),一次性讀取整個(gè)文檔,把文檔中所有元素保存在內(nèi)存中的一個(gè)樹結(jié)構(gòu)里,之后你可以利用DOM 提供的不同的函數(shù)來讀取或修改文檔的內(nèi)容和結(jié)構(gòu),也可以把修改過的內(nèi)容寫入xml文件。
python中用xml.dom.minidom來解析xml文件,實(shí)例如下:
#!/usr/bin/python3 from xml.dom.minidom import parse import xml.dom.minidom # 使用minidom解析器打開 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)
以上程序執(zhí)行結(jié)果如下:
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
完整的 DOM API 文檔請(qǐng)查閱Python DOM APIs。