[XML-SIG] Returning dictionary from endDocument under xml.sax

Brian Birkinbine bbirkinbine@earthlink.net
Wed, 8 May 2002 12:41:52 -0500


I'm having difficulty returning a dictionary from the XML code below.

I'm new to Python and XML, so please provide constructive comments where necessary.

Please let me know if this is not the right forum for this.  If not, I'll look at
posting to the pythontutor list or elsewhere.

Since I am not calling the endDocument() method directly (XML Parser does this),
will returning a dictionary from within the endDocument() method work?  I know
that my dictionary (self.d) is correct when endDocument() is called.
	If I put in debugging code in endDocument() and print
	self.d.keys() and self.d.values(), the values are correct.

So far I am unable to return the dictionary back to my XMLParse.py program.
I appear to be getting 'None' which seems to suggest to me that my return is
not making it all the way out of the Class method.

I am trying to avoid writing to a file in endDocument().

Thanks in advance,
Brian Birkinbine


- - - parts of XMLHandler.py - - -

import xml.sax

class xmlHandler(xml.sax.ContentHandler):
	def __init__(self):
		self.xmlname = ""
		self.xmlvalue = ""
		self.d = {}
	def startElement(self, name, attr):
		# ignore attr for now since I don't need it
		self.xmlvalue = ""
	def endElement(self, name):
		self.xmlname = name
		self.d[self.xmlname] = self.xmlvalue
	def characters(self, value):
		self.xmlvalue = self.xmlvalue + value
	def endDocument(self):
		return self.d

- - - XMLHandler.py - - -


- - - parts of XMLParse.py - - -

import xml.sax
import XMLHandler
import libXML

# populate buffer from file
buffer = inputfd.read()
inputfd.close()

# find xml data in buffer and return string with xml section
# xmlbuffer is a list containing strings of xml data chunks from libXML.findxmldata()
xmlbuffer = libXML.findxmldata(buffer)

# use xml handler
xmlhandler = XMLHandler.xmlHandler()

counter = 0
result = []
while (counter < len(xmlbuffer)):
	result = xml.sax.parseString(xmlbuffer[counter],xmlhandler)
	# I've also tried result.append(xml.sax.parseString ...) and it doesn't work
	print result
	counter = counter + 1
- - - XMLParse.py - - -