XML documentation stinks - help?

Simon John simoninusa2001 at yahoo.co.uk
Wed Sep 1 14:23:08 EDT 2004


Ah, I've got it now, I've basically managed to duplicate the way the
event-based XML::Parser Perl module works - you don't need to know the
tags and it builds a hash/dictionary (excuse Google removing the
formatting):

from xml.sax import ContentHandler, parseString

xmlsource = """<session_service>
<session_id>abcdefg123456</session_id>
<start_date>7/2/1978</start_date>
<end_date>7/2/2004</end_date>
<username>joe_bloggs</username>
<admin_flag>1</admin_flag>
</session_service>
"""

# create dictionary for results
global xml_data
xml_data = {}

class docHandler(ContentHandler):
"""overload contenthandler"""
def startElement(self, tag, attrs):
# start handler
self.tag = tag

def characters(self, chars):
# char handler - ignore whitespace
if chars.strip() != "":
xml_data[self.tag] = chars

# create instance of handler class
handler = docHandler()

# parse the xml
parseString(xmlsource, handler)

# loop through dictionary outputting results
for name, value in xml_data.iteritems():
    print name, ":", value




More information about the Python-list mailing list