本文实例讲述了Python3基于sax解析xml操作。分享给大家供大家参考,具体如下:
python使用SAX解析xml
SAX是一种基于事件驱动的API。
利用SAX解析XML文档牵涉到两个部分:和。
解析器负责读取XML文档,并向事件处理器发送事件,如元素开始跟元素结束事件;
而事件处理器则负责对事件作出相应,对传递的XML数据进行处理。
1,对大型文件进行处理;
2,只需要文件的部分内容,或者只需从文件中得到特定信息。
3,想建立自己的对象模型的时候。
在python中使用sax方式处理xml要先引入sax <代码> 代码>中的<代码> >代码解析函数,还有<代码> xml.sax.handler> 代码中的ContentHandler <代码> 代码>。
saxDemo.py
# - * -编码:utf - 8 - * # !/usr/bin/python3 sax进口 类MovieHandler (sax。ContentHandler): def __init__(自我): self.CurrentDatahttps://www.yisu.com/zixun/=薄? 自我。类型=" " 自我。格式=" " 自我。年=" " 自我。评级=" " 自我。明星=" " self.description=" " #元素开始调用 def startElement(自我、标签、属性): 自我。CurrentData=https://www.yisu.com/zixun/tag 如果标签==暗缬啊? 打印(“电影* * * * * * * * * *”) title=属性(“标题”) 打印(“标题:标题) #元素结束调用 def endElement(自我、标记): 如果自我。CurrentData=https://www.yisu.com/zixun/=袄嘈汀? 打印(类型:self.type) elif自我。CurrentData=https://www.yisu.com/zixun/=案袷健? 打印(格式:self.format) elif自我。CurrentData=https://www.yisu.com/zixun/=澳辍? 打印(“:”,self.year) elif自我。CurrentData=https://www.yisu.com/zixun/=捌兰丁? 打印(评级:“self.rating) elif自我。CurrentData=https://www.yisu.com/zixun/=懊餍恰? 打印(“星星:“self.stars) elif自我。CurrentData=https://www.yisu.com/zixun/=懊枋觥? 打印(“描述:”,self.description) self.CurrentDatahttps://www.yisu.com/zixun/=薄? #读取字符时调用 def字符(自我、内容): 如果自我。CurrentData=https://www.yisu.com/zixun/=袄嘈汀? 自我。类型=内容 elif自我。CurrentData=https://www.yisu.com/zixun/=案袷健? 自我。格式=内容 elif自我。CurrentData=https://www.yisu.com/zixun/=澳辍? 自我。年=内容 elif自我。CurrentData=https://www.yisu.com/zixun/=捌兰丁? 自我。评级=内容 elif自我。CurrentData=https://www.yisu.com/zixun/=懊餍恰? 自我。明星=内容 elif自我。CurrentData=https://www.yisu.com/zixun/=懊枋觥? self.description=内容 如果(__name__==癬_main__”): XMLReader #创建一个 解析器=xml.sax.make_parser () #关掉namepsaces parser.setFeature (xml.sax.handler。feature_namespaces, 0) #重写ContextHandler 处理程序=MovieHandler () 解析器。setContentHandler(处理器) parser.parse (“movies.xml”) >之前执行结果
电影* * * * * * * * * *
引用>
标题:
背后的敌人 类型:爱情中国
格式:DVD
2003年:
评级:PG
明星:10
描述:谈论美日战争
* * * * * * * * * *电影
标题:《变形金刚》
类型:动画,科幻小说
格式:DVD
1989年:
评级:R
明星:8
描述:一个schientific小说运行结果如下图所示:
movies.xml内容:
& lt; & # 63; xml version=" 1.0 " encoding=" utf - 8 " & # 63;比; & lt;收集货架=靶吕凑摺北? & lt;电影标题=背后的“敌人”比; & lt; type>爱中国& lt;/type> & lt; format> DVD & lt; year> 2003 & lt;/year> & lt; rating> PG & lt; stars> 10 & lt;/stars> & lt; description>谈论美日war & lt;/movie> & lt;电影标题=氨湫谓鸶铡北? & lt; type>动画、科学Fiction & lt; format> DVD & lt; year> 1989 & lt;/year> & lt; rating> R & lt; stars> 8 & lt;/stars> & lt; description> schientific fiction & lt;/movie> & lt;/collection>Python3基于sax解析xml操作示例