2012-02-05 80 views
1

是否有任何方法將參數傳遞給SAX解析器。我得到的解析器如下:將參數傳遞給python中的SAX處理程序

from xml.sax import make_parser, handler 
class parserSAXHandler(handler.ContentHandler): 

    def __init__(self): 


    def startElement(self, name, attrs): 

    def endElement(self,name): 


    def characters(self, content): 


parser = make_parser() 
parser.setContentHandler(parserSAXHandler()) 

doc="PathToDocToBeParsed"; 
parser.parse(doc); 

如何將一個參數傳遞給處理程序對象?

回答

2

只需讓您的__init__函數接受參數,並將這些參數存儲到稍後。

from xml.sax import make_parser, handler 
class parserSAXHandler(handler.ContentHandler): 

    def __init__(self, something): 
     self.something = something 

    def startElement(self, name, attrs): 

    def endElement(self,name): 
     ... 
     do_something(self.something) 
     ... 

    def characters(self, content): 


parser = make_parser() 
parser.setContentHandler(parserSAXHandler(some_argument)) 

doc="PathToDocToBeParsed"; 
parser.parse(doc); 
相關問題