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

Home
Python Tutorial
1.Introduction
2.Data Type
3.Statement
4.Operator
5.String
6.Tuple
7.List
8.Dictionary
9.Collections
10.Function
11.Class
12.File
13.Buildin Function
14.Buildin Module
15.Database
16.Regular Expressions
17.Thread
18.Tkinker
19.wxPython
20.XML
21.Network
22.CGI Web
23.Windows
Python Tutorial » XML » XMLParser 
20.8.1.Create your own parser based on xmllib.XMLParser
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
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.