您好,欢迎访问一九零五行业门户网

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 )
pyhton 标准库包含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数据进行处理。
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
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
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
其它类似信息

推荐信息