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
XMLReaderobject. 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 parametersource, which may be a filename, URL, readable file object orInputSourceinstance.
parseString(text, content_handler[, error_handler])
Similar to
parse, but the input document is the text intext.
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 orInputSourceobject. The interfaceInputSourceis described later on this page.
getContentHandler( )
Returns the configured content handler, or
Noneif none exists.
getDTDHandler( )
Returns the configured DTD handler, or
Noneif none exists.
getEntityResolver( )
Returns the configured entity resolver, or
Noneif none exists.
getErrorHandler( )
Returns the configured error handler, or
Noneif none exists.
getFeature(name)
Gets the current Boolean value of the feature specified by
name. Returnstrueif enabled andfalseif disabled. RaisesSAXNotRecognizedorSAXNotSupportedifnameis 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 ofSAXException.
setContentHandler(handler)
Sets the content handler to
handler, which must implement interfaceContentHandlerdescribed next. IfhandlerisNone, content events are not reported.
setDTDHandler(handler)
Sets the DTD handler to
handler, which must implement interfaceDTDHandlerdescribed later. IfhandlerisNone, no information on unparsed entities is reported to the application.
setEntityResolver(resolver)
Sets the entity resolver to
handler, which must implement interfaceEntityResolverdescribed later. IfhandlerisNone, 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 interfaceErrorHandlerdescribed later. IfhandlerisNone, default behavior applies.
setFeature(name, value)
Enables or disables the parser feature specified by
name. Enabled ifvalueistrueand disabled iffalse. An unknown feature raisesSAXNotRecognized; an unsupported value raisesSAXNotSupported. 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
nametovalue. The parser checks whethervaluehas the appropriate type and may raise an exception otherwise. If propertynameis 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
locatorlocating an event’s source, so you can find the end position of document-related events. The objectlocatorimplements interfaceLocatordescribed later on this page.
startDocument( )
Called first and exactly once when a document begins, unless
setDocumentLocatorexists 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
prefixis the document’s prefix string, anduriis the Universal Resource Identifier (URI) represented by the prefix.
endPrefixMapping(prefix)
Occurs when the end element corresponding to
startPrefixMappingis called, meaning the declaration forprefixhas gone out of scope. It does not mean no mapping exists forprefixbecause an outer declaration may remain in scope.
startElement(name, attrs)
Occurs whenever an element’s opening tag is encountered.
nameis the element’s tag name. Parameterattrsis a dictionary of attribute names and values. Called when namespaces are not processed.
startElementNS(name, qname, attrs)
Here
nameis a URI/local-name tuple. Parameterqnameis the XML tag name andattrsa 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
contentholds 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. Parameterwhitespaceholds 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
targetanddataare 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
systemIdis 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, ifsystemIdis 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
systemIdis the entity declaration’s URL, andpublicIdthe public identifier orNoneif absent. Returns a new system-identifier string or an object supporting interfaceInputSource.
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
Noneif absent or unknown.
getSystemId( )
Returns the source’s system identifier, or
Noneif absent or unknown. A fully initialized source should returnNoneonly 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 parametercharsetof response headerContent-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
errorbut 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
attributeon element typeelement. The data type, specified astype, is a string with one of the valuesCDATA,ENTITY,ENTITIES,ID,IDREF,IDREFS,NMTOKEN,NMTOKENSorNOTATION, or a list of strings for enumerations. Parameterconstraintis a string orNone; possible strings are#FIXED,#IMPLIEDand#REQUIRED. An attribute default is supplied asdefault; otherwisedefaultisNone.
elementDecl(name, contentModel)
Called for an element declaration.
nameis the element type’s name, andcontentModelits content model. The model is a string with valueEMPTYorANYor a tuple containing the model separator, element-type name list and modifier.
externalEntityDecl(name, publicId, systemId)
Reports an externally parsed entity’s definition.
nameis the entity’s assigned name,publicIdits public identifier orNone, andsystemIdits system identifier.
internalEntityDecl(name, value)
Called when an internal general entity is defined.
nameis its assigned name, andvaluea 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 parametertext.
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 aDeclHandlerand implement methodsexternalEntityDeclandinternalEntityDecl.
endEntity(name)
Called when parsing finishes for the entity identified by
name. SeestartEntityfor entity-name usage.
startCDATA( )
Called at the beginning of a
CDATAsection.
endCDATA( )
Called at the end of a
CDATAsection.
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, not0.
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
Noneif none.
getMessage( )
Returns a readable explanation of the parser problem, possibly localized if method
setLocaleis called onXMLReader.
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.
Copyright © 2002 O'Reilly Verlag GmbH & Co. KG
You may print the online version for your private use.
Otherwise, this chapter from “Python & XML” is subject to the same conditions as the bound edition: the work, including all its parts, is 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