[代码笔记] python 之 xml解析_sax:基于事件驱动的解析方式

来源:互联网 发布:net域名需要备案吗 编辑:程序博客网 时间:2024/05/18 15:27
#!usr/bin/python3#文件名: demo_xml.py#SAX解析import xml.sax#继承并重写xml.sax.ContentHandler 的众多方法事件回调class MovieHandler(xml.sax.ContentHandler ):    def __init(self):#经测试,在类中任何有self的地方直接使用self.变量名赋值初始化变量,相当与子啊类中定义一个变量,即下面的所有代码注释后加pass后程序也可以正常运行        #'''        self.CurrentData=""        self.type=''        self.format=''        self.yesr=''        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)    #元素结束是调用:当遇到结束标签时,说明character方法以调用过了,可以打印记录下的值    def endElement(self,tag):        if tag=='type':            print('Type:',self.type)        elif tag=='format':            print('Format:',self.format)        elif tag=='rating':            print('Rating:',self.rating)        elif tag=='stars':            print('Stars:',self.stars)        elif tag=='description':            print('Description:',self.description)        self.CurrentData=''    #读取字符时调用    '''        1.character方法,在遇到字符串时调用        2.此方法在不同时机被调用时,参数content的值代表意义不同:            a.开头到遇到标签过程中:为开头到标签之间的字符            b.一个标签到下一个标签过程中: 为2个标签之间的字符            c.一个标签到尾部过程中: 为标签到结尾间的字符            开头---标签1---标签2---标签N...-----结尾        3.可以通过在开始标签是记录下标签的名称tag,来判断其值是属于那个标签的    '''    def characters(self,content):        if self.CurrentData=='type':            self.type=content        elif self.CurrentData=='format':            self.format=content        elif self.CurrentData=='rating':            self.rating=content        elif self.CurrentData=='stars':            self.stars=content        elif self.CurrentData=='description':            self.description=contentif (__name__=='__main__'):    parser=xml.sax.make_parser()    parser.setFeature(xml.sax.handler.feature_namespaces,0)    Handler=MovieHandler()    parser.setContentHandler(Handler)    parser.parse('demo.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>

“`

0 0
原创粉丝点击