Home >Backend Development >Python Tutorial >Python中使用SAX解析xml实例

Python中使用SAX解析xml实例

WBOY
WBOYOriginal
2016-06-06 11:20:051140browse

SAX是一种基于事件驱动的API。利用SAX解析XML文档牵涉到两个部分:解析器和事件处理器。解析器负责读取XML文档,并向事件处理器发送事件,如元素开始跟元素结束事件;而事件处理器则负责对事件作出相应,对传递的XML数据进行处理。

实例:

代码如下:


import  sys, string from  xml.sax import  handler, make_parser
 
 class  TestHandler(handler.ContentHandler):                       
         def  __init__(self):                                                               
                 pass
                
         def  startDocument(self):           
                 print  "Document Start ..."
               
        def  endDocument(self):                
                print  "Document End ..."
               
        def  startElement(self, name, attrs):
                print  'start tag:', name
               
        def  endElement(self, name):
                print  'end tag:', name    
               
        def  characters(self, chrs):                                                    
                print  chrs
               
    
def  test():    
        handler = TestHandler()    
        parser = make_parser()    
        parser.setContentHandler(handler)
        f = open(sys.argv[1], 'r')    
        parser.parse(f)    
        f.close()
    
if  __name__ == '__main__':
        test()

除了DOM外的另一种读写文件的方式。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn