On Wed, Aug 30, 2006 at 05:25:59AM -0700, Akanksha Govil wrote:
> Hi,
> 
> I have written a small code in python for reading xml using SAX.
> 
> I am importing xml.sax using the following:
> 
> from xml.sax import saxlib, saxexts
> On executing the code I get the following error:
> 
> ImportError: cannot import name saxlib
> 
> Both python-xml and pyxml are installed on my machine along with
> python 2.4.
> 

I believe that there have been a few changes to the organization of
the SAX modules and the interfaces of the classes themselves.

Attached is a simple SAX example that should help get you started,
if you haven't already groped your way through it.

Also, you will want to read the following and the pages it links
to:

    http://docs.python.org/lib/module-xml.sax.html
    http://docs.python.org/lib/module-xml.sax.xmlreader.html
    http://docs.python.org/lib/module-xml.sax.handler.html
    Etc.

Dave

-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman
import sys, string
import xml.sax.handler as handler
import xml.sax


class MySaxDocumentHandler(handler.ContentHandler):
    def __init__(self, outfile):    # [2]
        self.outfile = outfile
        self.level = 0
    def startDocument(self):
        print "--------  Document Start --------"
    def endDocument(self):
        print "--------  Document End --------"
    def startElement(self, name, attrs):
        self.level += 1
        self.printLevel()
        self.outfile.write('Element: %s\n' % name)
        self.level += 2
        for attrName in attrs.keys():
            self.printLevel()
            self.outfile.write('Attribute -- Name: %s  Value: %s\n' % \
                (attrName, attrs.get(attrName)))
        self.level -= 2
    def endElement(self, name):
        self.level -= 1
    def characters(self, chrs):
        if chrs.strip() != '':
            self.level += 2
            self.printLevel()
            self.outfile.write('Content: %s\n' % chrs)
            self.level -= 2
    def printLevel(self):
        for idx in range(self.level):
            self.outfile.write('  ')

#
# Create a handler and a parser, then parse the file.
#
def test(infilename):
    handler = MySaxDocumentHandler(sys.stdout)
    parser = xml.sax.make_parser()
    parser.setContentHandler(handler)
    parser.parse(infilename)

#
# A simpler way to do the same thing as test().
#
def test_simple(infilename):
    handler = MySaxDocumentHandler(sys.stdout)
    xml.sax.parse(infilename, handler)
    

def main():
    args = sys.argv[1:]
    if len(args) != 1:
        print 'usage: test_sax.py <infile.xml>'
        sys.exit(1)
    test_simple(args[0])

if __name__ == '__main__':
    main()

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to