最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python實現(xiàn)XML解析的方法解析

 更新時間:2019年11月16日 12:03:20   作者:子不語332  
這篇文章主要介紹了python實現(xiàn)XML解析的方法解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下

這篇文章主要介紹了python實現(xiàn)XML解析的方法解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下

三種方法:一是xml.dom.*模塊,它是W3C DOM API的實現(xiàn),若需要處理DOM API則該模塊很適合;二是xml.sax.*模塊,它是SAX API的實現(xiàn),這個模塊犧牲了便捷性來換取速度和內(nèi)存占用,SAX是一個基于事件的API,這就意味著它可以“在空中”處理龐大數(shù)量的的文檔,不用完全加載進內(nèi)存;三是xml.etree.ElementTree模塊(簡稱 ET),它提供了輕量級的Python式的API,相對于DOM來說ET 快了很多,而且有很多令人愉悅的API可以使用,相對于SAX來說ET的ET.iterparse也提供了 “在空中” 的處理方式,沒有必要加載整個文檔到內(nèi)存,ET的性能的平均值和SAX差不多,但是API的效率更高一點而且使用起來很方便。

1、DOM(Document Object Model)

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

python中用xml.dom.minidom來解析xml文件。

本文使用的示例文件movie.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>

python實現(xiàn)如下

# !/usr/bin/python
# -*- coding: UTF-8 -*-

from xml.dom.minidom import parse
import xml.dom.minidom

# 使用minidom解析器打開 XML 文檔
DOMTree = xml.dom.minidom.parse("movie.xml")
#得到元素對象
collection = DOMTree.documentElement
if collection.hasAttribute("shelf"):
  print("Root element : %s" % collection.getAttribute("shelf"))
  #獲取標(biāo)簽名
  #print(collection.nodeName)

# 在集合中獲取所有電影
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)
  year=movie.getElementsByTagName("year")
  if len(year)>0:
    print("Year: %s" % year[0].firstChild.data)
    #父節(jié)點 parentNode
    #print(year[0].parentNode.nodeName)
  rating = movie.getElementsByTagName('rating')[0]
  print("Rating: %s" % rating.childNodes[0].data)
  description = movie.getElementsByTagName('description')[0]
  # 顯示標(biāo)簽對之間的數(shù)據(jù)
  print("Description: %s" % description.childNodes[0].data)
  #print("Description: %s" % description.firstChild.data)

執(zhí)行結(jié)果:

Root element : New Arrivals
*****Movie*****
Title: Enemy Behind
Type: War, Thriller
Format: DVD
Year: 2003
Rating: PG
Description: Talk about a US-Japan war
*****Movie*****
Title: Transformers
Type: Anime, Science Fiction
Format: DVD
Year: 1989
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

2、ElementTree(元素樹)

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

在python中,解析xml文件時,會選用ElementTree或者cElementTree,那么兩者有什么不同呢?

1、cElementTree速度上要比ElementTree快,比較cElementTree是用c語音寫的;

2、debug調(diào)試的時候,cElementTree是看不到解析的字段內(nèi)容的,所以不適合用于調(diào)試的情況,而ElementTree可以看到解析的內(nèi)容,方便調(diào)試時取值

3、在用到iter,迭代取某個標(biāo)簽時,cElementTree不能用,因為它沒有這個函數(shù),而ElementTree有這個函數(shù);當(dāng)然可能還有其他函數(shù)的差異

所有平時,我們一般這么用,比較速度快嗎。調(diào)試的時候使用ElementTree。遇到某些特別的函數(shù),只能選擇擁有這個函數(shù)的使用  

  try:
    import xml.etree.cElementTree as ET
  except:  
    import xml.etree.ElementTree as ET

從Python3.3開始ElementTree模塊會自動尋找可用的C庫來加快速度

import xml.etree.ElementTree as ET
import sys
import os.path

def traverseXml(element):
  #print (len(element))
  if len(element) > 0:
    for child in element:
      print("********Movie********")
      print("Title:",child.get("title"))
      for childchild in child:
        print(childchild.tag,":",childchild.text)
      #traverseXml(child)
  #else:
  #  print (element.tag, "----", element.attrib)

def readXml(xmlFile):
  try:
    tree = ET.parse(xmlFile)
    #print("tree type:", type(tree))
    # 獲得根節(jié)點
    root = tree.getroot()
  except Exception as e: # 捕獲除與程序退出sys.exit()相關(guān)之外的所有異常
    print("parse ***.xml fail!")
    sys.exit()
  #print("root type:", type(root))
  #root.attrib訪問root屬性,root.tag標(biāo)簽
  #print(root.tag, ":", root.attrib)
  return root

if __name__ == "__main__":
  xmlFilePath = os.path.abspath("movie.xml")
  root=readXml(xmlFilePath)

  # # 使用下標(biāo)訪問
  # print(root[0][0].text)
  # print(root[1][2].text)
  #根據(jù)標(biāo)簽名查找root下的所有標(biāo)簽
  # movies=root.findall("movie")
  #遍歷子標(biāo)簽
  # print(len(movies))
  # for movie in movies:
  #   type=movie.find("type")
  #   print(type.text)

  # 遍歷xml文件
  traverseXml(root)

3、SAX (simple API for XML )

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

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

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

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

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

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

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

ContentHandler類方法介紹

characters(content)方法

調(diào)用時機:

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

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

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

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

startDocument() 方法

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

endDocument() 方法

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

startElement(name, attrs)方法

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

endElement(name) 方法

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

#!/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)

  # 元素結(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("movie.xml")

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • python wsgiref源碼解析

    python wsgiref源碼解析

    這篇文章主要介紹了python wsgiref源碼的相關(guān)資料,幫助大家更好的理解和使用python,感興趣的朋友可以了解下
    2021-02-02
  • python庫使用Fire庫生成命令行參數(shù)

    python庫使用Fire庫生成命令行參數(shù)

    Python Fire是一個開源庫,能把Python對象轉(zhuǎn)換為命令行界面,F(xiàn)ire庫是一個非常有用的工具,它可以幫助開發(fā)人員創(chuàng)建命令行界面,并且可以將任何Python對象轉(zhuǎn)換為命令行界面,這篇文章主要介紹了python庫使用Fire庫生成命令行參數(shù),需要的朋友可以參考下
    2024-02-02
  • PyG搭建GCN需要準(zhǔn)備的數(shù)據(jù)格式

    PyG搭建GCN需要準(zhǔn)備的數(shù)據(jù)格式

    這篇文章主要為大家介紹了PyG搭建GCN前需要準(zhǔn)備的PyG數(shù)據(jù)格式,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-05-05
  • pycharm實現(xiàn)print輸出保存到txt文件

    pycharm實現(xiàn)print輸出保存到txt文件

    這篇文章主要介紹了pycharm實現(xiàn)print輸出保存到txt文件,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-06-06
  • Python 的描述符 descriptor詳解

    Python 的描述符 descriptor詳解

    Python中包含了許多內(nèi)建的語言特性,它們使得代碼簡潔且易于理解。這些特性包括列表/集合/字典推導(dǎo)式,屬性(property)、以及裝飾器(decorator)。對于大部分特性來說,這些“中級”的語言特性有著完善的文檔,并且易于學(xué)習(xí)。但是這里有個例外,那就是描述符。
    2016-02-02
  • Python實現(xiàn)的單向循環(huán)鏈表功能示例

    Python實現(xiàn)的單向循環(huán)鏈表功能示例

    這篇文章主要介紹了Python實現(xiàn)的單向循環(huán)鏈表功能,簡單描述了單向循環(huán)鏈表的概念、原理并結(jié)合實例形式分析了Python定義與使用單向循環(huán)鏈表的相關(guān)操作技巧,需要的朋友可以參考下
    2017-11-11
  • python實現(xiàn)可視化動態(tài)CPU性能監(jiān)控

    python實現(xiàn)可視化動態(tài)CPU性能監(jiān)控

    這篇文章主要為大家詳細(xì)介紹了python可視化動態(tài)CPU性能監(jiān)控,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-06-06
  • 關(guān)于python爬蟲應(yīng)用urllib庫作用分析

    關(guān)于python爬蟲應(yīng)用urllib庫作用分析

    這篇文章主要介紹了關(guān)于python爬蟲應(yīng)用urllib庫作用分析,想要進行python爬蟲首先我們需要先將網(wǎng)頁上面的信息給獲取下來,這就是utllib庫的作用,有需要的朋友可以借鑒參考下
    2021-09-09
  • 舉例講解Python中的算數(shù)運算符的用法

    舉例講解Python中的算數(shù)運算符的用法

    這篇文章主要介紹了舉例講解Python中的算數(shù)運算符的用法,是Python學(xué)習(xí)當(dāng)中的基礎(chǔ)知識,需要的朋友可以參考下
    2015-05-05
  • 解決python報錯ImportError:urllib3?v2.0?only?supports?OpenSSL?1.1.1+

    解決python報錯ImportError:urllib3?v2.0?only?supports?OpenSSL

    這篇文章主要介紹了解決python報錯ImportError:urllib3?v2.0?only?supports?OpenSSL?1.1.1+的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2023-12-12

最新評論

和顺县| 桂林市| 徐州市| 稻城县| 年辖:市辖区| 额尔古纳市| 宁安市| 五寨县| 营口市| 建水县| 遂溪县| 阳原县| 民乐县| 金寨县| 宿州市| 东港市| 永兴县| 台北县| 耒阳市| 平和县| 河池市| 麦盖提县| 绥德县| 泸西县| 辉南县| 临清市| 日土县| 东明县| 井陉县| 诸城市| 佛坪县| 化州市| 广灵县| 大埔县| 永城市| 小金县| 华宁县| 丹寨县| 乌苏市| 呼图壁县| 房产|