日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

c语言解析xml字符串_Python XML解析

發(fā)布時間:2023/11/27 生活经验 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 c语言解析xml字符串_Python XML解析 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

Python XML解析


什么是XML?

XML 指可擴展標記語言(eXtensible?Markup?Language)。 你可以通過本站學習XML教程

XML 被設(shè)計用來傳輸和存儲數(shù)據(jù)。

XML是一套定義語義標記的規(guī)則,這些標記將文檔分成許多部件并對這些部件加以標識。

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


python對XML的解析

常見的XML編程接口有DOM和SAX,這兩種接口處理XML文件的方式不同,當然使用場合也不同。

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

1.SAX (simple API for XML )

pyhton 標準庫包含SAX解析器,SAX用事件驅(qū)動模型,通過在解析XML的過程中觸發(fā)一個個的事件并調(diào)用用戶定義的回調(diào)函數(shù)來處理XML文件。

2.DOM(Document Object Model)

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

3.ElementTree(元素樹)

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

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

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

<collection shelf="New Arrivals"><movie title="Enemy Behind">   <type>War, Thrillertype>   <format>DVDformat>   <year>2003year>   <rating>PGrating>   <stars>10stars>   <description>Talk about a US-Japan wardescription>movie><movie title="Transformers">   <type>Anime, Science Fictiontype>   <format>DVDformat>   <year>1989year>   <rating>Rrating>   <stars>8stars>   <description>A schientific fictiondescription>movie>   <movie title="Trigun">   <type>Anime, Actiontype>   <format>DVDformat>   <episodes>4episodes>   <rating>PGrating>   <stars>10stars>   <description>Vash the Stampede!description>movie><movie title="Ishtar">   <type>Comedytype>   <format>VHSformat>   <rating>PGrating>   <stars>2stars>   <description>Viewable boredomdescription>movie>collection>

python使用SAX解析xml

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

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

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

而事件處理器則負責對事件作出相應,對傳遞的XML數(shù)據(jù)進行處理。

  • 1、對大型文件進行處理;

  • 2、只需要文件的部分內(nèi)容,或者只需從文件中得到特定信息。

  • 3、想建立自己的對象模型的時候。

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

ContentHandler類方法介紹

characters(content)方法

調(diào)用時機:

從行開始,遇到標簽之前,存在字符,content的值為這些字符串。

從一個標簽,遇到下一個標簽之前, 存在字符,content的值為這些字符串。

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

標簽可以是開始標簽,也可以是結(jié)束標簽。

startDocument()方法

文檔啟動的時候調(diào)用。

endDocument()方法

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

startElement(name, attrs)方法

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

endElement(name)方法

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


make_parser方法

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

xml.sax.make_parser( [parser_list] )

參數(shù)說明:

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


parser方法

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

xml.sax.parse( xmlfile, contenthandler[, errorhandler])

參數(shù)說明:

  • xmlfile?- xml文件名

  • contenthandler?- 必須是一個ContentHandler的對象

  • errorhandler?- 如果指定該參數(shù),errorhandler必須是一個SAX ErrorHandler對象


parseString方法

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

xml.sax.parseString(xmlstring, contenthandler[, errorhandler])

參數(shù)說明:

  • xmlstring?- xml字符串

  • contenthandler?- 必須是一個ContentHandler的對象

  • errorhandler?- 如果指定該參數(shù),errorhandler必須是一個SAX ErrorHandler對象


Python 解析XML實例

#coding=utf-8#!/usr/bin/pythonimport xml.saxclass 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   # 元素結(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)建一個 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")

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

*****Movie*****Title: Enemy BehindType: War, ThrillerFormat: DVDYear: 2003Rating: PGStars: 10Description: Talk about a US-Japan war*****Movie*****Title: TransformersType: Anime, Science FictionFormat: DVDYear: 1989Rating: RStars: 8Description: A schientific fiction*****Movie*****Title: TrigunType: Anime, ActionFormat: DVDRating: PGStars: 10Description: Vash the Stampede!*****Movie*****Title: IshtarType: ComedyFormat: VHSRating: PGStars: 2Description: Viewable boredom

完整的 SAX API 文檔請查閱Python SAX APIs


使用xml.dom解析xml

文件對象模型(Document Object Model,簡稱DOM),是W3C組織推薦的處理可擴展置標語言的標準編程接口。

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

python中用xml.dom.minidom來解析xml文件,實例如下:

#coding=utf-8#!/usr/bin/pythonfrom xml.dom.minidom import parseimport xml.dom.minidom# 使用minidom解析器打開 XML 文檔DOMTree = xml.dom.minidom.parse("movies.xml")collection = DOMTree.documentElementif 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

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

Root element : New Arrivals*****Movie*****Title: Enemy BehindType: War, ThrillerFormat: DVDRating: PGDescription: Talk about a US-Japan war*****Movie*****Title: TransformersType: Anime, Science FictionFormat: DVDRating: RDescription: A schientific fiction*****Movie*****Title: TrigunType: Anime, ActionFormat: DVDRating: PGDescription: Vash the Stampede!*****Movie*****Title: IshtarType: ComedyFormat: VHSRating: PGDescription: Viewable boredom

完整的 DOM API 文檔請查閱Python DOM APIs。

總結(jié)

以上是生活随笔為你收集整理的c语言解析xml字符串_Python XML解析的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。