XML technologies / XML / Python & XML / The Simple API for XML / Native parser interfaces

(Excerpt from "Python & XML" by Christopher A. Jones & Fred L. Drake, Jr.)

Now that we have seen how SAX can be used, and how similar the code for setting up the parser and the ContentHandler is, you may wonder how much of this simplicity comes from SAX and how much from helper functions in the Python libraries. We will not delve deeply into individual parsers’ native interfaces, but this is a good question that leads to some interesting observations.

The main advantage of SAX is that callback methods have the same names and meanings regardless of the parser used. This has at least two benefits: changing parsers does not affect your application, and your code is easier to maintain because a newcomer is more likely to know the SAX interface than a parser-specific interface.

How do individual parsers’ native interfaces differ from SAX, and why might we use them instead? A brief look at PyExpat illustrates the differences.

Using PyExpat directly

Naturally, PyExpat must be installed before use. It is available in the Python installer for Windows and is built automatically on Unix if the Expat library is installed. If you did not install PyExpat with Python, it is installed as part of PyXML.

PyExpat resides in the module xml.parsers.expat. Adapting our previous example to use PyExpat directly requires only a few changes. Since PyExpat’s handler methods closely match the SAX handler’s, at least for the simple use shown here, we can reuse the handler class we already wrote. The import statements need little alteration:

#!/usr/bin/env python

import sys

from xml.parsers import expat
from handlers    import PyXMLConversionHandler

Once the parser is imported, it can be created and used:

 parser = expat.ParserCreate( ) 

At an interactive prompt, we could inspect the parser object to see its attributes:

>>> from xml.parsers import expat
>>> parser = expat.ParserCreate( )
>>> dir(parser)
['CharacterDataHandler', 'CommentHandler', 'DefaultHandler', 'DefaultHandlerExpa
nd', 'EndCdataSectionHandler', 'EndElementHandler', 'EndNamespaceDeclHandler', '
ErrorByteIndex', 'ErrorCode', 'ErrorColumnNumber', 'ErrorLineNumber', 'ExternalE
ntityParserCreate', 'ExternalEntityRefHandler', 'GetBase', 'NotStandaloneHandler
', 'NotationDeclHandler', 'Parse', 'ParseFile', 'ProcessingInstructionHandler',
'SetBase', 'StartCdataSectionHandler', 'StartElementHandler', 'StartNamespaceDec
lHandler', 'UnparsedEntityDeclHandler', 'ordered_attributes', 'returns_unicode',
   'specified_attributes']

This certainly does not look like a SAX parser!

There is neither a setContentHandler method nor anything replacing it. To register our content handler, we must set several attributes to methods of a content-handler instance:

dh = PyXMLConversionHandler(sys.stdout)

parser.StartElementHandler = dh.startElement
parser.EndElementHandler = dh.endElement
parser.CharacterDataHandler = dh.characters

This is not difficult, but it certainly takes more work than the method setContentHandler in SAX. The code really does need changing because we must use several methods from the handler object.

After initializing the handler methods we need, we can start parsing. Again, this differs slightly from the SAX version:

 parser.Parse(sys.stdin.read( ), 1) 

We know what sys.stdin.read( ) does, but the 1, used as the second parameter looks suspiciously like a magic number in our source code. It is actually a Boolean value indicating that the string passed to the Parse method is the final chunk of input; Parse can be called repeatedly with smaller input chunks and a flag set to 0, then finally with a value of 1 for the last chunk. This is useful when reading data asynchronously over a network connection.

The following method is also available for parsing XML from a file object:

 parser.ParseFile(sys.stdin) 

The following example shows the complete script using the handler with PyExpat.

Example: genhtml2.py with PyExpat

"""
genhtml2.py - erzeugt HTML aus pyxml.xml
"""

import sys

from xml.parsers import expat
from handlers     import PyXMLConversionHandler

dh = PyXMLConversionHandler(sys.stdout)
parser = expat.ParserCreate( )

parser.StartElementHandler = dh.startElement
parser.EndElementHandler = dh.endElement
parser.CharacterDataHandler = dh.characters
parser.ParseFile(sys.stdin)

Output goes to standard output. Opened in a browser, it displays all classes in the PyXML package and their methods, just like the pure SAX version of this example.

  

 

 

 

back to top