XML technologies / XML / Python & XML / The Python-SAX API

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

The Simple API for XML (SAX) is essentially a collection of interfaces. Python supports its second version, often called SAX 2. The implementation provides convenient base classes, making it easy to implement only the methods you need, plus functions simplifying SAX use in most applications.

SAX is explained in The Simple API for XML with examples. Official documentation of Python’s SAX implementation belongs to the Python Library Reference.

   

   

 

Helper functions

Three important helpers make SAX parsing trivial and suffice for most applications, especially when ContentHandler is the only handler required. These functions are in module xml.sax and work with both the standard library and PyXML.

make_parser([parser_list])

Returns a SAX XMLReader object. Most examples in The Simple API for XML use it to create a reader. See also Advanced parser factory usage for the underlying parser factories.

parse(source, content_handler[, error_handler])

Creates a reader with make_parser, associates the content and error handlers and parses a document identified by parameter source, which may be a filename, URL, readable file object or InputSource instance.

parseString(text, content_handler[, error_handler])

Similar to parse, but the input document is the text in text.

 

XMLReader

The basic SAX 2 parser interface, providing methods to get and set handlers and control configurable options.

parse(source)

Starts parsing the document in the entity identified by source. This parameter may be a filename, URL or InputSource object. The interface InputSource is described later on this page.

getContentHandler( )

Returns the configured content handler, or None if none exists.

getDTDHandler( )

Returns the configured DTD handler, or None if none exists.

getEntityResolver( )

Returns the configured entity resolver, or None if none exists.

getErrorHandler( )

Returns the configured error handler, or None if none exists.

getFeature(name)

Gets the current Boolean value of the feature specified by name. Returns true if enabled and false if disabled. Raises SAXNotRecognized or SAXNotSupported if name is unknown or unsupported, respectively.

getProperty(name)

Returns the current value of the property specified by name. The result is a suitable Python object, and the application must follow the property’s rules. Unknown or unsupported properties raise the appropriate subclass of SAXException.

setContentHandler(handler)

Sets the content handler to handler, which must implement interface ContentHandler described next. If handler is None, content events are not reported.

setDTDHandler(handler)

Sets the DTD handler to handler, which must implement interface DTDHandler described later. If handler is None, no information on unparsed entities is reported to the application.

setEntityResolver(resolver)

Sets the entity resolver to handler, which must implement interface EntityResolver described later. If handler is None, the parser determines whether and how to access external entities by default. Many parsers offer basic external-entity loading.

setErrorHandler(handler)

Sets the error handler to handler, which must implement interface ErrorHandler described later. If handler is None, default behavior applies.

setFeature(name, value)

Enables or disables the parser feature specified by name. Enabled if value is true and disabled if false. An unknown feature raises SAXNotRecognized; an unsupported value raises SAXNotSupported. Some features must be set before parsing; others may be set anytime.

setLocale(locale)

Sets the locale for parser error messages. Unsupported locales raise a SAX exception which applications may catch and ignore, but the locale remains unchanged. Applications may change it anytime.

setProperty(name, value)

Sets the property identified by name to value. The parser checks whether value has the appropriate type and may raise an exception otherwise. If property name is unknown or unsupported, the appropriate exception is raised. Some properties must be set before parsing; others anytime.

 

ContentHandler

The ContentHandler is the most-used SAX handler, receiving parsed elements, their attributes and content between tags. Helpers parse and parseString described above require an implementation of ContentHandler as an argument.

setDocumentLocator(locator)

SAX parsers are encouraged to supply a locator locating an event’s source, so you can find the end position of document-related events. The object locator implements interface Locator described later on this page.

startDocument( )

Called first and exactly once when a document begins, unless setDocumentLocator exists and is called beforehand.

endDocument( )

Called exactly once as the parser’s final method.

startPrefixMapping(prefix, uri)

Called when a namespace declaration is encountered. Parameter prefix is the document’s prefix string, and uri is the Universal Resource Identifier (URI) represented by the prefix.

endPrefixMapping(prefix)

Occurs when the end element corresponding to startPrefixMapping is called, meaning the declaration for prefix has gone out of scope. It does not mean no mapping exists for prefix because an outer declaration may remain in scope.

startElement(name, attrs)

Occurs whenever an element’s opening tag is encountered. name is the element’s tag name. Parameter attrs is a dictionary of attribute names and values. Called when namespaces are not processed.

startElementNS(name, qname, attrs)

Here name is a URI/local-name tuple. Parameter qname is the XML tag name and attrs a dictionary of attribute name/value pairs. Called only with namespaces enabled.

endElement(name)

Occurs at an element’s end if its beginning was reported by startElement.

endElementNS(name, qname)

The corresponding event/method for startElementNS.

characters(content)

Called for every character-data section outside elements or other markup. It may be called repeatedly for apparently contiguous data: some parsers call once per line, others for joined lines between markup. All character data is delivered through these calls. Parameter content holds the actual character data.

ignorableWhitespace(whitespace)

Validating parsers call this when reporting whitespace (Whitespace) in element content. Like characters, calls may repeat depending on the parser. Validating parsers must call it. Parameter whitespace holds the actual whitespace found.

processingInstruction(target, data)

Called once for every processing instruction found. XML and text declarations must not be reported this way. Parameters target and data are strings containing the instruction’s application-relevant information.

skippedEntity(name)

Called whenever an entity reference’s content is not parsed. Non-validating parsers may skip external entities or any entity whose declaration they have not seen.

 

DTDHandler

Provides information useful for unparsed external entities. This handler is not often used.

notationDecl(name, publicId, systemId)

Called for a notation declaration. At least one ID parameter must be supplied. If systemId is present and is a URL, the parser must resolve it fully before reporting it.

unparsedEntityDecl(name, publicId, systemId, ndata)

The notation name matches a notation reported by notationDecl. Again, if systemId is a URL, it must be fully resolved before delivery.

 

EntityResolver

Controls external-entity loading for application-level caching or techniques mapping public identifiers to system identifiers.

resolveEntity(publicId, systemId)

Converts an external entity’s identifiers to a loadable system identifier. Parameter systemId is the entity declaration’s URL, and publicId the public identifier or None if absent. Returns a new system-identifier string or an object supporting interface InputSource.

 

InputSource

Applications may use instances from module xml.sax.xmlreader of class InputSource as return values of method resolveEntity in interface EntityResolver, or as arguments to helper parse or method XMLReader. Alternative implementations should not normally be needed but are allowed. When preparing an InputSource for the parser, use its various set methods to supply all available source information.

Upon receiving an InputSource instance, the parser first tries its character stream, then its byte stream. If neither is available, it uses the system identifier to open a byte stream itself.

getByteStream( )

Returns the source’s byte stream, yielding raw bytes rather than decoded Unicode characters.

getCharacterStream( )

Returns the character stream, supplying decoded Unicode characters instead of raw bytes.

getEncoding( )

Returns the known byte-stream encoding, otherwise None. With unknown encoding, the parser applies automatic detection rules to the stream’s initial bytes.

getPublicId( )

Returns the source’s public identifier, or None if absent or unknown.

getSystemId( )

Returns the source’s system identifier, or None if absent or unknown. A fully initialized source should return None only when identifying the document entity and supplied directly by the user rather than by URL or filename.

setByteStream(stream)

Sets the byte stream when it can be accessed more efficiently than via the system identifier, for example from a cache rather than the network.

setCharacterStream(stream)

Sets the character stream when the source can supply Unicode characters directly.

setEncoding(encoding)

Sets byte-stream encoding to encoding. A transport protocol may provide this information; HTTP, for example, can include character encoding in parameter charset of response header Content-Type.

setPublicId(id)

Sets the public identifier to id.

setSystemId(id)

Sets the system identifier to id.

 

ErrorHandler

SAX error handling is described in SAX handler objects. Each method of interface ErrorHandler receives a SAXException instance. Specific exception classes appear under “SAX exceptions” below.

error(exception)

Lets applications respond to a nonfatal error.

fatalError(exception)

Similar to error but reports a fatal parsing error. Applications should regard the document as unusable at this point.

warning(exception)

Reports nonfatal conditions that are not necessarily errors.

 

DeclHandler

The DeclHandler reports document structure allowed by the DTD. Only PyXML supports it, not the standard library. A simple base class is DeclHandler in module xml.sax.saxlib. Set the DeclHandler on the parser with method setProperty and constant property_declaration_handler from module xml.sax.handler.

attributeDecl(element, attribute, type, constraint, default)

Called for every declared attribute, representing attribute attribute on element type element. The data type, specified as type, is a string with one of the values CDATA, ENTITY, ENTITIES, ID, IDREF, IDREFS, NMTOKEN, NMTOKENS or NOTATION, or a list of strings for enumerations. Parameter constraint is a string or None; possible strings are #FIXED, #IMPLIED and #REQUIRED. An attribute default is supplied as default; otherwise default is None.

elementDecl(name, contentModel)

Called for an element declaration. name is the element type’s name, and contentModel its content model. The model is a string with value EMPTY or ANY or a tuple containing the model separator, element-type name list and modifier.

externalEntityDecl(name, publicId, systemId)

Reports an externally parsed entity’s definition. name is the entity’s assigned name, publicId its public identifier or None, and systemId its system identifier.

internalEntityDecl(name, value)

Called when an internal general entity is defined. name is its assigned name, and value a string holding its replacement text.

 

LexicalHandler

The LexicalHandler reports syntactic events such as CDATA section boundaries and comments. Only PyXML supports it, not the standard library. A simple base class is LexicalHandler in module xml.sax.saxlib. Set the LexicalHandler on the parser with method setProperty and constant property_lexical_handler from module xml.sax.handler.

comment(text)

Called for a comment. Its body between the two -- is passed in parameter text.

startDTD( )

Called before any DTD information is read, whether internal or external. Called at most once.

endDTD( )

Called after all DTD information is read, at most once.

startEntity(name)

Called when parsing starts for the DTD entity named name. To discover the names defined in the DTD, use a DeclHandler and implement methods externalEntityDecl and internalEntityDecl.

endEntity(name)

Called when parsing finishes for the entity identified by name. See startEntity for entity-name usage.

startCDATA( )

Called at the beginning of a CDATA section.

endCDATA( )

Called at the end of a CDATA section.

 

Locator

locator objects expose where events occur in a document. Applications receive a locator by implementing method setDocumentLocator on the content handler. Methods identify the entity being parsed and the position reached when an event occurred. Exception class SAXParseException also implements interface Locator.

This information is valuable for reporting document problems. An out-of-range price or unknown product number in an order can be accompanied by its precise XML location. An editor widget can then position the cursor at the problem so users can correct it.

getColumnNumber( )

Returns the character offset in the event’s line. Tabs do not adjust this column value.

getLineNumber( )

Returns the event’s line number. The first line is 1, not 0.

getPublicId( )

Returns the parsed entity’s public identifier if known, otherwise None.

getSystemId( )

Returns the entity’s system identifier at the event, if known. It may be unknown when document-entity data is fed directly to the parser. If unknown, returns None.

 

SAX exceptions

SAX reports all errors, including handler exceptions, as instances of class SAXException or subclasses. Instances provide these methods:

getException( )

Returns the exception caught by the SAX parser, or None if none.

getMessage( )

Returns a readable explanation of the parser problem, possibly localized if method setLocale is called on XMLReader.

SAX defines these subclasses of SAXException.

SAXParseException

Raised for document parsing problems. Its instances also implement interface Locator.

SAXNotRecognizedException

Raised when an application gets or sets an unrecognized feature or property. Parsers must recognize every SAX 2 feature and property, even if unsupported.

SAXNotSupportedException

Raised when an application gets or sets a recognized but unsupported feature or property, or assigns an unsupported value.

  

Back to top

 

 

 

back to top