SAX XML Parse Python error message

goldtech goldtech at worldpost.com
Sun Jul 13 11:30:14 EDT 2008


SAX XML Parse Python error message
Hi,
My first attempt at SAX, but have an error message I need help with.

I cite the error message, code, and xml below.

Be grateful if anyone can tell me what the fix is.
Thanks.


>>>
Traceback (most recent call last):
File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework
\scriptutils.py", line 310, in RunScript
exec codeObject in __main__.__dict__
File "C:\pythonscripts\xml\parse3.py", line 43, in ?
parser.parse(r'C:\perlscripts\xml\Document2.kml')
File "C:\Python24\lib\xml\sax\expatreader.py", line 107, in parse
xmlreader.IncrementalParser.parse(self, source)
File "C:\Python24\lib\xml\sax\xmlreader.py", line 123, in parse
self.feed(buffer)
File "C:\Python24\lib\xml\sax\expatreader.py", line 207, in feed
self._parser.Parse(data, isFinal)
File "C:\Python24\lib\xml\sax\expatreader.py", line 303, in
end_element
self._cont_handler.endElement(name)
File "C:\pythonscripts\xml\parse3.py", line 39, in endElement
print self.description, str(self.coordinates)
AttributeError: G_Handler instance has no attribute 'coordinates'
>>>


Code:

from xml.sax import make_parser
from xml.sax.handler import ContentHandler
import string

class G_Handler(ContentHandler):

    def __init__ (self):
        self.isFolderElement = 0
        self.isdescriptionElement = 0
        self.iscoordinatesElement = 0

    def startElement(self, name , attrs):
        if name == 'Folder':
            self.isFolderElement= 1
            self.Folder = ""
        if name == 'description':
            self.isdescriptionElement= 1
            self.description = ""
        if name == 'coordinates':
            self.iscoordinatesElement = 1
            self.coordinates = ""


    def characters (self, ch):
        if self.isFolderElement == 1:
            self.Folder = ch
        if self.isdescriptionElement == 1:
            self.description = ch
        if self.iscoordinatesElement == 1:
            self.coordinates = ch

    def endElement(self, name):
        if name == 'Folder':
            self.isFolderElement = 0
        if name == 'description':
            self.isdescriptionElement= 0
        if name == 'coordinates':
            self.iscoordinatesElement = 0
        print  self.description, str(self.coordinates)

parser = make_parser()
parser.setContentHandler(G_Handler())
parser.parse(r'C:\perlscripts\xml\Document2.kml')



<?xml version="1.0" encoding="UTF-8"?>
<Folder>
<description>
abc
</description>
<coordinates>
-84.4, 33.7
</coordinates>
<description>
abc
</description>
<coordinates>
-86.7, 36.1
</coordinates>
</Folder>



More information about the Python-list mailing list