码迷,mamicode.com
首页 > 编程语言 > 详细

[python 学习] sax

时间:2017-11-07 00:15:09      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:and   es2017   character   str   art   attr   handle   etc   print   

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

import xml.sax

class MovieHandler( xml.sax.ContentHandler ):
   def __init__(self):
         self.stack = []
   # 元素开始事件处理
   def startElement(self, tag, attributes):
      if len(self.stack) !=0:
            print "\n","*"*4*len(self.stack),
      attr = ""
      # 属性值
      if attributes.getLength() > 0:
            for attrName in attributes.getNames():
                  attr = " " + attr + attrName + "=" + attributes.getValue(attrName)
      print "<"+tag+attr+">",
      self.stack.append("start")

   # 元素结束事件处理
   def endElement(self, tag):
      if self.stack[len(self.stack)-1] == "content" and self.stack[len(self.stack)-2] == "start":
            del self.stack[len(self.stack)-1]
            del self.stack[len(self.stack)-2]
      elif self.stack[len(self.stack)-1] =="start":
            del self.stack[len(self.stack)-1]
            print "\n","*"*4*len(self.stack),

      print "</"+tag+">",

   # 内容事件处理
   def characters(self, content):
      if content.strip() != ‘‘: 
            self.stack.append("content")
            print 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("movie.xml")

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>

解析输出:

技术分享

参见:http://www.cnblogs.com/hongfei/p/python-xml-sax.html

[python 学习] sax

标签:and   es2017   character   str   art   attr   handle   etc   print   

原文地址:http://www.cnblogs.com/natian-ws/p/7795729.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!