[XML-SIG] example code?

Thomas B. Passin tpassin@idsonline.com
Sun, 19 Dec 1999 13:38:49 -0500


Michal Wallace wrote:

>
> Hello,
>
>   I've got a total newbie question here:
>
>   I've been writing a simple little template system for web scripts.
> The syntax for the files is XML-based, and I've been using xmllib...
> I've read the docs, but I've yet to find any decent example code, and
> right now almost all of my processing is being done through overriding
> the unknown_starttag() and unknown_endtag() functions. What should
> I be doing instead?
>
>   The docs say to override the "elements" dictionary, but:
>
>   def elements["sometag"][0]():
>       pass
>
> gives an error, and:
>
>   def start_sometag(blahblah):
>       pass
>
>   elements["sometag"][0] = start_sometag
>
> just seems like the wrong thing to be doing.. What's the "right"
> way to do this? Does anyone have an example program I could borrow?
>
> Thanks,
>
> - Michal

If you know all the element names you will use, do something easy like this,
which handles an element named "specialTag":

import xmllib

"""A simple class to demonstate how to handle your own elements"""
class bareBones(xmllib.XMLParser):
    def __init__(self):
        xmllib.XMLParser.__init__(self)

    # Your element is called "specialTag"
    def start_specialTag(self, attrs):
        print "Start specialTag"
        print "element name:", attrs
        self.handle_data=self.do_data  #invoke your content handler
    def end_specialTag(self):
        print "End specialTag"
        self.handle_data=self.null_data #reset content handler

    # A minimal data handler
    def do_data(self,data):
        print "===============\n",data,"\n==============="

    def null_data(self,data):pass

doc="""<?xml version="1.0"?>
<doc>
<e1>This element won't be reported</e1>
<specialTag a="attribute 1">This one will</specialTag>
</doc>
"""

if __name__=="__main__":
    parser=bareBones()
    parser.feed(doc)
    parser.close()

Tom Passin