16.01.2014 Views

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

430 CHAPTER 22 ■ PROJECT 3: XML FOR ALL OCCASIONS<br />

Figure 22-1. A generated Web page<br />

Second Implementation<br />

Because the SAX mechanism is so low-level and basic, you may often find it useful <strong>to</strong> write a<br />

mix-in class that handles some administrative details such as gathering character data, managing<br />

Boolean state variables (such as passthrough), or dispatching the events <strong>to</strong> your own cus<strong>to</strong>m<br />

event handlers. The state and data handling is pretty simple in this project, so let’s focus on the<br />

handler dispatch.<br />

A Dispatcher Mix-In Class<br />

Rather than having <strong>to</strong> write large if statements in the standard generic event handlers (such as<br />

startElement), it would be nice <strong>to</strong> just write your own specific ones (such as startPage) and<br />

have them called au<strong>to</strong>matically. You can implement that functionality in a mix-in class, and<br />

then subclass the mix-in along with ContentHandler.<br />

■Note As mentioned in Chapter 7, a mix-in is a class with limited functionality that is meant <strong>to</strong> be subclassed<br />

along with some other more substantial class.<br />

You want the following functionality in your program: When startElement is called with a<br />

name such as 'foo', it should attempt <strong>to</strong> find an event handler called startFoo and call it with<br />

the given attributes. Similarly, if endElement is called with 'foo', it should try <strong>to</strong> call endFoo. If,<br />

in any of these methods, the given handler is not found, a method called defaultStart (or<br />

defaultEnd, respectively) will be called, if present. If the default handler isn’t present either,<br />

nothing should be done.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!