XML technologies / XML / Python & XML / The Simple API for XML / Advanced use of the parser factory
(Excerpt from "Python & XML" by Christopher A. Jones & Fred L. Drake, Jr.)
PyXML provides several parsers and ways to instantiate them, depending on whether you use SAX, want to build a DOM tree, or do something else. The ParserFactory class, designed for portable code, provides a SAX-capable parser guaranteed to be available in your runtime environment. You can also create a parser or SAX driver explicitly through a specific package such as PyExpat. We show both approaches, but normally you should use the parser factory.
The function make_parser (imported from xml.sax) returns a SAX driver for the first available parser in the supplied list, or an available parser if no list is supplied or its parsers cannot be found or loaded. The function make_parser comes from the class xml.sax.saxexts.ParserFactory, but it is better to import the method from xml.sax (more on this later). For example:
from xml.sax import make_parser
parser = make_parser( ) At the time of writing, if PyXML is installed, calling make_parser without arguments guarantees a PyExpat or xmlproc driver. Looking through the source of the module xml.sax shows that this list is passed to the ParserFactory class. If you instantiate a parser factory directly from xml.sax.saxexts, supply a list containing at least one valid parser name; otherwise, it cannot create a parser:
>>> from xml.sax.saxexts import ParserFactory
>>> p = ParserFactory( )
>>> parser = p.make_parser( )
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/usr/local/lib/python2.0/site-packages/_xmlplus/sax/saxexts.py",
line 77, in make_parser
raise SAXReaderNotAvailable("No parsers found", None)
xml.sax._exceptions.SAXReaderNotAvailable: No parsers foundSupplying a list of parsers or drivers gets you what you need:
>>> from xml.sax.saxexts import ParserFactory
>>> p = ParserFactory(["xml.sax.drivers.drv_pyexpat"])
>>> parser = p.make_parser( )In most cases, it is a good idea to use the function make_parser from xml.sax, but understanding what happens internally is useful. Several factory classes provide variants for HTML, SGML and non-validating and validating XML parsers.
Copyright © 2002 O'Reilly Verlag GmbH & Co. KG
You may print the online version for your private use.
Otherwise, this chapter from the book "Python & XML" is subject to the same conditions as the printed edition: the work and all its parts are protected by copyright. All rights reserved, including reproduction, translation, microfilming, and storage and processing in electronic systems.
O’Reilly Verlag GmbH & Co. KG, Balthasarstraße 81, 50670 Köln, kommentar(at)oreilly.de
back to top