正规的彩票

Python如何对XML 解析

 更新时间: 2020年06月28日 16:08:07   转载 作者: 菜鸟教程  
这篇文章主要介绍了Python对XML 解析的方法,文中讲解非常细致,代码帮助大家更好的理解和学习,感兴趣的朋友可以了解下

什么是 XML?

XML 指可扩展标记语言(eXtensible Markup Language),标准通用标记语言的子集,是一种用于标记电子文件使其具有结构性的标记语言。 你可以通过本站学习 XML 教程

xml beishejiyonglaichuanshuhecunchushuju。

xml shiyitaodingyiyuyibiaojideguize,zheixiebiaojijiangwendangfenchengxuduobujianbingduizheixiebujianjiayibiaoshi。

正规的彩票tayeshiyuanbiaojiyuyan,jidingyileyongyudingyiqitayutedinglingyuyouguande、yuyide、jiegouhuadebiaojiyuyandejufayuyan。

Python 对 XML 的解析

changjiande xml bianchengjiekouyou dom he sax,zheiliangzhongjiekouchuli xml wenjiandefangshibutong,dangranshiyongchangheyebutong。

python yousanzhongfangfajiexi xml,sax,dom,yiji elementtree:

1.SAX (simple API for XML )

正规的彩票python biaozhunkubaohan sax jiexiqi,sax yongshijianqudongmoxing,tongguozaijiexi xml deguochengzhongchufayigegedeshijianbingdiaoyongyonghudingyidehuidiaohanshulaichuli xml wenjian。

2.DOM(Document Object Model)

jiang xml shujuzaineicunzhongjiexichengyigeshu,tongguoduishudecaozuolaicaozuo xml。

正规的彩票benzhangjieshiyongdaode xml shiliwenjian movies.xml neirongruxia:

<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 shiyizhongjiyushijianqudongdeapi。

liyong sax jiexi xml wendangqianshedaolianggebufen: jiexiqiheshijianchuliqi。

正规的彩票jiexiqifuzeduqu xml wendang,bingxiangshijianchuliqifasongshijian,ruyuansukaishigenyuansujieshushijian。

ershijianchuliqizefuzeduishijianzuochuxiangying,duichuandide xml shujujinxingchuli。

  • 1、对大型文件进行处理;
  • 2、只需要文件的部分内容,或者只需从文件中得到特定信息。
  • 3、想建立自己的对象模型的时候。

zai python zhongshiyong sax fangshichuli xml yaoxianyinru xml.sax zhongde parse hanshu,haiyou xml.sax.handler zhongde contenthandler。

ContentHandler 类方法介绍

characters(content) 方法

diaoyongshiji:

congxingkaishi,yudaobiaoqianzhiqian,cunzaizifu,content dezhiweizheixiezifuchuan。

congyigebiaoqian,yudaoxiayigebiaoqianzhiqian, cunzaizifu,content dezhiweizheixiezifuchuan。

congyigebiaoqian,yudaoxingjieshufuzhiqian,cunzaizifu,content dezhiweizheixiezifuchuan。

biaoqiankeyishikaishibiaoqian,yekeyishijieshubiaoqian。

startDocument() 方法

wendangqidongdeshihoudiaoyong。

endDocument() 方法

jiexiqidaodawendangjieweishidiaoyong。

startElement(name, attrs) 方法

yudaoxmlkaishibiaoqianshidiaoyong,name shibiaoqiandemingzi,attrs shibiaoqiandeshuxingzhizidian。

正规的彩票endelement(name) fangfa

遇到XML结束标签时调用。

make_parser 方法

正规的彩票yixiafangfachuangjianyigexindejiexiqiduixiangbingfanhui。

xml.sax.make_parser( [parser_list] )

canshushuoming:

  • parser_list - 可选参数,解析器列表

parser 方法

yixiafangfachuangjianyige sax jiexiqibingjiexixmlwendang:

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

canshushuoming:

  • xmlfile - xml文件名
  • contenthandler - 必须是一个 ContentHandler 的对象
  • errorhandler - 如果指定该参数,errorhandler 必须是一个 SAX ErrorHandler 对象

parseString 方法

parsestring fangfachuangjianyige xml jiexiqibingjiexi xml zifuchuan:

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

canshushuoming:

  • xmlstring - xml字符串
  • contenthandler - 必须是一个 ContentHandler 的对象
  • errorhandler - 如果指定该参数,errorhandler 必须是一个 SAX ErrorHandler对象

Python 解析XML实例

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

 # 元素开始调用
 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()
 # 关闭命名空间
 parser.setFeature(xml.sax.handler.feature_namespaces, 0)

 # 重写 ContextHandler
 Handler = MovieHandler()
 parser.setContentHandler( Handler )
 
 parser.parse("movies.xml")

正规的彩票yishangdaimazhixingjieguoruxia:

*****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

正规的彩票wanzhengde sax api wendangqingchayue

使用xml.dom解析xml

正规的彩票wenjianduixiangmoxing(document object model,jianchengdom),shiw3czuzhituijiandechulikekuozhanzhibiaoyuyandebiaozhunbianchengjiekou。

yige dom dejiexiqizaijiexiyige xml wendangshi,yicixingduquzhenggewendang,bawendangzhongsuoyouyuansubaocunzaineicunzhongdeyigeshujiegouli,zhihounikeyiliyongdom tigongdebutongdehanshulaiduquhuoxiugaiwendangdeneironghejiegou,yekeyibaxiugaiguodeneirongxieruxmlwenjian。

pythonzhongyongxml.dom.minidomlaijiexixmlwenjian,shiliruxia:

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

# 打印每部电影的详细信息
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)

yishangchengxuzhixingjieguoruxia:

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

正规的彩票wanzhengde dom api wendangqingchayue

yishangjiushipythonruheduixml jiexidexiangxineirong,gengduoguanyupythonduixml jiexideziliaoqingguanzhujiaobenzhijiaqitazhengguidecaipiaoxiangguandewenzhang!

正规的彩票相关的文章

最新评论

正规的彩票_正规彩票平台app下载[首页最快线路√] 彩票官网_彩票官网app|网站首页 彩票平台_彩票平台快三-[平台最快线路√] 彩票app下载_彩票app下载官网下载快三_官方入口 彩票平台_彩票平台app-专注彩票门户 彩票官网_彩票官网app下载网址-HOME 彩票平台_彩票平台登录-老品牌最信誉 彩票app_彩票app客户端下载>> 首页 彩票平台_彩票平台免费送彩金18-点击进入>! 彩票平台_彩票平台官网〖2020购彩首选〗 彩票app_彩票app彩票投注平台-Welcome