Python使用sax模块解析XML文件示例

yipeiwu_com5年前Python基础

本文实例讲述了Python使用sax模块解析XML文件。分享给大家供大家参考,具体如下:

XML样例:

<?xml version="1.0"?>
<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>

SAX解析代码展示:

from xml import sax
class MovieHandler(sax.ContentHandler):
  def __init__(self):
    # 初始化数据,并增加一个当前数据
    self.CurrentData = ""
    self.type = ""
    self.format = ""
    self.year = ""
    self.rating = ""
    self.stars = ""
    self.description = ""
  # 文档启动的时候调用
  def startDocument(self):
    print('XML开始解析中...')
  # 元素开始事件处理
  def startElement(self, name, attrs):
    self.CurrentData=name
    if self.CurrentData=='movie':
      print('*********movie*********')
      title=attrs['title']
      print('Title:{0}'.format(title))
  # 内容事件处理
  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
  # 元素结束事件处理
  def endElement(self, name):
    if self.CurrentData=='type':
      print('Type:{0}'.format(self.type))
    elif self.CurrentData=='format':
      print('Format:{0}'.format(self.format))
    elif self.CurrentData=='year':
      print('Year:{0}'.format(self.year))
    elif self.CurrentData == 'rating':
      print('Rating:{0}'.format(self.rating))
    elif self.CurrentData == 'stars':
      print('Stars:{0}'.format(self.stars))
    elif self.CurrentData == 'description':
      print('Description:{0}'.format(self.description))
    self.CurrentData = ""
  # 文档结束的时候调用
  def endDocument(self):
    print('XML文档解析结束!')
if __name__=='__main__':
  handler=MovieHandler()
  parser = sax.make_parser()
  # parser.setFeature(sax.handler.feature_namespaces, 0)
  parser.setContentHandler(handler)
  parser.parse("sax_test.xml")

PS:这里再为大家提供几款关于xml操作的在线工具供大家参考使用:

在线XML/JSON互相转换工具:
http://tools.jb51.net/code/xmljson

在线格式化XML/在线压缩XML
http://tools.jb51.net/code/xmlformat

XML在线压缩/格式化工具:
http://tools.jb51.net/code/xml_format_compress

XML代码在线格式化美化工具:
http://tools.jb51.net/code/xmlcodeformat

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python操作xml数据技巧总结》、《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

python3 读取Excel表格中的数据

需要先安装openpyxl库 通过pip命令安装: pip install openpyxl 源码如下: #!/usr/bin/python3 #-*- coding:utf-8 -...

Django如何开发简单的查询接口详解

前言 Django处理json也是一把好手,有时候在工作中各个部门都会提供自己的相关接口,但是信息也只是单方的信息,这时候需要运维将各个部门的信息进行集成,统一出一个查询接口或页面,方便...

玩转python selenium鼠标键盘操作(ActionChains)

用selenium做自动化,有时候会遇到需要模拟鼠标操作才能进行的情况,比如单击、双击、点击鼠标右键、拖拽等等。而selenium给我们提供了一个类来处理这类事件——ActionChai...

python定时器使用示例分享

复制代码 代码如下:class SLTimer(multiprocessing.Process):    #from datetime import dat...

Python多线程编程(三):threading.Thread类的重要函数和方法

这篇文章主要介绍threading模块中的主类Thread的一些主要方法,实例代码如下: 复制代码 代码如下: '''  Created on 2012-9-7 ...