内射老阿姨1区2区3区4区_久久精品人人做人人爽电影蜜月_久久国产精品亚洲77777_99精品又大又爽又粗少妇毛片

python如何實現(xiàn)XML解析-創(chuàng)新互聯(lián)

這篇文章將為大家詳細講解有關(guān)python如何實現(xiàn)XML解析,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

創(chuàng)新互聯(lián)建站擁有十年成都網(wǎng)站建設工作經(jīng)驗,為各大企業(yè)提供成都做網(wǎng)站、成都網(wǎng)站設計、成都外貿(mào)網(wǎng)站建設服務,對于網(wǎng)頁設計、PC網(wǎng)站建設(電腦版網(wǎng)站建設)、APP應用開發(fā)、wap網(wǎng)站建設(手機版網(wǎng)站建設)、程序開發(fā)、網(wǎng)站優(yōu)化(SEO優(yōu)化)、微網(wǎng)站、域名與空間等,憑借多年來在互聯(lián)網(wǎng)的打拼,我們在互聯(lián)網(wǎng)網(wǎng)站建設行業(yè)積累了很多網(wǎng)站制作、網(wǎng)站設計、網(wǎng)絡營銷經(jīng)驗,集策劃、開發(fā)、設計、營銷、管理等網(wǎng)站化運作于一體,具備承接各種規(guī)模類型的網(wǎng)站建設項目的能力。

三種方法:一是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"))
  #獲取標簽名
  #print(collection.nodeName)

# 在集合中獲取所有電影
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)
  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]
  # 顯示標簽對之間的數(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,迭代取某個標簽時,cElementTree不能用,因為它沒有這個函數(shù),而ElementTree有這個函數(shù);當然可能還有其他函數(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標簽
  #print(root.tag, ":", root.attrib)
  return root

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

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

  # 遍歷xml文件
  traverseXml(root)

3、SAX (simple API for XML )

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

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

關(guān)于“python如何實現(xiàn)XML解析”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。

當前標題:python如何實現(xiàn)XML解析-創(chuàng)新互聯(lián)
本文路徑:http://www.rwnh.cn/article38/djpgsp.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供企業(yè)網(wǎng)站制作、微信公眾號、企業(yè)建站、微信小程序網(wǎng)站制作、云服務器

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

微信小程序開發(fā)
鹤峰县| 剑川县| 称多县| 连云港市| 曲阳县| 沿河| 仙居县| 台中市| 当涂县| 千阳县| 嵊州市| 霍林郭勒市| 高平市| 东乡| 阳新县| 石嘴山市| 东乌珠穆沁旗| 乌拉特前旗| 瑞丽市| 东海县| 大新县| 曲阜市| 共和县| 大英县| 锡林郭勒盟| 新晃| 宁乡县| 类乌齐县| 若羌县| 项城市| 瓦房店市| 岳池县| 抚远县| 兴和县| 济南市| 原平市| 永平县| 安达市| 五原县| 旺苍县| 子长县|