关于 Python xml.sax 解析

来源:互联网 发布:tcp默认端口 编辑:程序博客网 时间:2024/05/02 00:59
from xml.sax import *

1、make_parser()
创建并返回SAX  XMLReader的对象
2、parse(filename,handler)
    执行解析,handler必须指定何种解析方式
    解析出文件中的一条语句,保存name(标签名),attrs(属性) 等信息   

3、xml.sax.handler
四种对xml的解析方式:
content handlers, DTD handlers, error handlers, and entity resolvers
常用的内容处理方式:
ContentHandler(要解析的类,继承contenthandler)

ContentHandler.startElement(name, attrs) 开始解析的信号(无命名空间时)
attr是可能被重复利用的Attributes属性对象


eg:
schd.py:
    。。。。。
        self.parser = make_parser()创建
        self.parser.setContentHandler(XMLParse(self))设置解析方式

xmlparse.py:
class XMLParse(ContentHandler):继承自ContentHandler
    。。。。。
 def startElement(self,name,attrs):
        if not name in self.name:
            return
self.attrs = attrs


loadfile.py:
。。。。。
     self.schd.parser.parse(file)执行解析

原创粉丝点击