[python 学习] sax

Posted 那天ws

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[python 学习] sax相关的知识,希望对你有一定的参考价值。

#!/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的主要内容,如果未能解决你的问题,请参考以下文章

学习笔记:python3,代码片段(2017)

javaweb学习总结十二(JAXP对XML文档进行SAX解析)

Python学习总结

python使用SAX解析xml

Python学习笔记__12.10章 XML

学习 PyQt5。在我的代码片段中找不到错误 [关闭]