Create your own parser based on xmllib.XMLParser : XMLParser « XML « Python Tutorial






import xmllib, string
class myparser(xmllib.XMLParser):
    def __init__(self):
        xmllib.XMLParser.__init__(self)
        self.currentquestiondesc = ''
        self.currentOp1 = ''
        self.currentOp2 = ''
        self.currentquestion = ''
        self.currentdata = []

    def handle_data(self, data):
        self.currentdata.append(data)

    def start_SURVEY(self, attrs):
        print "Survey of section number ",

    def end_SURVEY(self):
        pass

    def start_SECTION(self, attrs):
        print attrs['SECTION_ID']

    def end_SECTION(self):
        pass

    def start_QUESTION(self, attrs):
        self.currentquestion = attrs['QUESTION_ID']

    def end_QUESTION(self):
        print """%(currentquestion)s- %(currentquestiondesc)s
     %(currentOp1)s
     %(currentOp2)s
""" % self.__dict__

    def start_QUESTION_DESC(self, attrs):
        self.currentdata = []

    def end_QUESTION_DESC(self):
        self.currentquestiondesc = string.join(self.currentdata,'')

    def start_Op1(self, attrs):
        self.currentdata = []

    def end_Op1(self):
        self.currentOp1 = string.join(self.currentdata,'')

    def start_Op2(self, attrs):
        self.currentdata = []

    def end_Op2(self):
        self.currentOp2 = string.join(self.currentdata,'')


filehandle = open("survey.xml")
data = filehandle.read()
filehandle.close()

parser=myparser()
parser.feed(data)
parser.close()








20.8.XMLParser
20.8.1.Create your own parser based on xmllib.XMLParser