工具標籤
目錄
工具標籤
Python XML解析
什麼是XML?
XML 指可擴充標記語言(eXtensible Markup Language)。 你可以透過本站學習XML教學
XML 被設計用來傳輸和儲存資料。
XML是一套定義語意標記的規則,這些標記將文件分成許多部件並對這些部件加以標識。
它也是元標記語言,即定義了用於定義其他與特定領域相關的、語義的、結構化的標記語言的句法語言。
python對XML的解析
常見的XML程式介面有DOM和SAX,這兩個介面處理XML檔案的方式不同,當然使用場合也不同。
python有三種方法解析XML,SAX,DOM,以及ElementTree:
1.SAX (simple API for XML )
python 標準函式庫包含SAX解析器,SAX用事件驅動模型,透過在解析XML的過程中觸發一個個的事件並呼叫使用者定義的回呼函數來處理XML檔案。
2.DOM(Document Object Model)
將XML資料在記憶體中解析成一個樹,透過對樹的操作來操作XML。
3.ElementTree(元素樹)
ElementTree就像一個輕量級的DOM,具有方便友善的API。程式碼可用性好,速度快,消耗記憶體少。
註:因DOM需要將XML資料映射到記憶體中的樹,一是比較慢,二是比較耗內存,而SAX流式讀取XML文件,比較快,佔用記憶體少,但需要使用者實作回呼函數(handler)。
本章節使用到的XML實例檔案movies.xml內容如下:
<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>
python使用SAX解析xml
#SAX是一種基於事件驅動的API 。
利用SAX解析XML文件牽涉到兩個部分:解析器和事件處理器。
解析器負責讀取XML文件,並向事件處理器發送事件,如元素開始跟元素結束事件;
而事件處理器則負責對事件作出相應,對傳遞的XML資料進行處理。
<psax適合處理下面的問題:< p="">1、對大型檔案處理;
2、只需要文件的部分內容,或只需從文件中得到特定資訊。
3、想建立自己的物件模型的時候。
在python中使用sax方式處理xml要先引入xml.sax中的parse函數,還有xml.sax.handler中的ContentHandler。
ContentHandler類別方法介紹
characters(content)方法
呼叫時機:
從行開始,遇到標籤之前,存在字符,content的值為這些字串。
從一個標籤,遇到下一個標籤之前, 存在字符,content的值為這些字串。
從一個標籤,遇到行結束符之前,存在字符,content的值為這些字串。
標籤可以是開始標籤,也可以是結束標籤。
startDocument()方法
文件啟動的時候呼叫。
endDocument()方法
#解析器到達文件結尾時呼叫。
startElement(name, attrs)方法
遇到XML開始標籤時調用,name是標籤的名字,attrs是標籤的屬性值字典。
endElement(name)方法
在遇到XML結束標籤時呼叫。
make_parser方法
以下方法建立一個新的解析器物件並傳回。
xml.sax.make_parser( [parser_list] )
參數說明:
parser_list - 可選參數,解析器清單
parser方法
以下方法建立一個SAX 解析器並解析xml文件:
xml.sax.parse( xmlfile, contenthandler[, errorhandler])
參數說明:
xmlfile - xml檔名
contenthandler - 必須是一個ContentHandler的物件
errorhandler - 如果指定該參數,errorhandler必須是一個SAX ErrorHandler物件
#parseString方法
parseString方法建立一個XML解析器並解析xml字串:
xml.sax.parseString(xmlstring, contenthandler[, errorhandler])
參數說明:
xmlstring - xml字串
contenthandler - 必須是一個ContentHandler的物件
errorhandler - 若指定此參數,errorhandler必須是SAX ErrorHandler物件
Python 解析XML實例
#!/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 = ""
# 元素开始事件处理
def startElement(self, tag, attributes):
self.CurrentData = tag
if tag == "movie":
print "*****Movie*****"
title = attributes["title"]
print "Title:", title
# 元素结束事件处理
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 = ""
# 内容事件处理
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__"):
# 创建一个 XMLReader
parser = xml.sax.make_parser()
# turn off namepsaces
parser.setFeature(xml.sax.handler.feature_namespaces, 0)
# 重写 ContextHandler
Handler = MovieHandler()
parser.setContentHandler( Handler )
parser.parse("movies.xml")以上程式碼執行結果如下:
*****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 文件請查閱Python SAX APIs
使用xml.dom解析xml
文件物件模型(Document Object Model,簡稱DOM),是W3C組織建議的處理可擴充置標語言的標準程式介面。
一個DOM 的解析器在解析一個XML 文檔時,一次讀取整個文檔,把文檔中所有元素保存在內存中的一個樹結構裡,之後你可以利用DOM 提供的不同的函數來讀取或修改文件的內容和結構,也可以把修改過的內容寫入xml檔。
python中用xml.dom.minidom來解析xml文件,實例如下:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
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")
# 打印每部电影的详细信息
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以上程式執行結果如下:
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 文件請參考Python DOM APIs。
相關影片
熱AI工具
免費脫衣圖片
用於從照片中去除衣服的線上人工智慧工具。
人工智慧驅動的應用程序,用於創建逼真的裸體照片
人工智慧支援投資研究,做出更明智的決策
熱門文章
熱門話題
20516
7
13629
4
11965
4
8980
17
8505
7
熱門工具
好用且免費的程式碼編輯器
中文版,非常好用
強大的PHP整合開發環境
視覺化網頁開發工具
神級程式碼編輯軟體(SublimeText3)












![PHP實戰開發極速入門: PHP快速創建[小型商業論壇]](https://img.php.cn/upload/course/000/000/035/5d27fb58823dc974.jpg)
