13.4 xml.parsers.expat -- Fast XML parsing using the Expat library
Keywords: lib

# 13.4 `xml.parsers.expat` -- Fast XML parsing using the Expat library

New in version 2.0.

The `xml.parsers.expat` module is a Python interface to the Expat non-validating XML parser. The module provides a single extension type, `xmlparser`, that represents the current state of an XML parser. After an `xmlparser` object has been created, various attributes of the object can be set to handler functions. When an XML document is then fed to the parser, the handler functions are called for the character data and markup in the XML document.

This module uses the `pyexpat` module to provide access to the Expat parser. Direct use of the `pyexpat` module is deprecated.

The `xml.parsers.expat` module contains two functions:

`ErrorString` (errno)
  Returns an explanatory string for a given error number errno.

`ParserCreate` ([encoding, namespace_separator])
  Creates and returns a new `xmlparser` object. encoding, if specified, must be a string naming the encoding used by the XML data. Expat doesn't support as many encodings as Python does, and its repertoire of encodings can't be extended; it supports UTF-8, UTF-16, ISO-8859-1 (Latin1), and ASCII.

  Expat can optionally do XML namespace processing for you, enabled by providing a value for namespace_separator. When namespace processing is enabled, element type names and attribute names that belong to a namespace will be expanded. The element name passed to the element handlers `StartElementHandler()` and `EndElementHandler()` will be the concatenation of the namespace URI, the namespace separator character, and the local part of the name. If the namespace separator is a zero byte (`chr(0)`) then the namespace URI and the local part will be concatenated without any separator.

  For example, if namespace_separator is set to "`` ", and the following document is parsed:

        <?xml version="1.0"?>
        <root xmlns    = "http://default-namespace.org/"
              xmlns:py = "http://www.python.org/ns/">
          <py:elem1 />
          <elem2 xmlns="" />
        </root>

  `StartElementHandler()` will receive the following strings for each element:

        http://default-namespace.org/ root
        http://www.python.org/ns/ elem1
        elem2

`xmlparser` objects have the following methods:

`Parse` (data [, isfinal])
  Parses the contents of the string data, calling the appropriate handler functions to process the parsed data. isfinal must be true on the final call to this method. data can be the empty string at any time.

`ParseFile` (file)
  Parse XML data reading from the object file. file only needs to provide the `read(nbytes)` method, returning the empty string when there's no more data.

`SetBase` (base)
  Sets the base to be used for resolving relative URIs in system identifiers in declarations. Resolving relative identifiers is left to the application: this value will be passed through as the base argument to the `ExternalEntityRefHandler`, `NotationDeclHandler`, and `UnparsedEntityDeclHandler` functions.

`GetBase` ()
  Returns a string containing the base set by a previous call to `SetBase()`, or `None` if `SetBase()` hasn't been called.

`xmlparser` objects have the following attributes:

`returns_unicode`
  If this attribute is set to 1, the handler functions will be passed Unicode strings. If `returns_unicode` is 0, 8-bit strings containing UTF-8 encoded data will be passed to the handlers.

The following attributes contain values relating to the most recent error encountered by an `xmlparser` object, and will only have correct values once a call to `Parse()` or `ParseFile()` has raised a `xml.parsers.expat.error` exception.

`ErrorByteIndex`
  Byte index at which an error occurred.

`ErrorCode`
  Numeric code specifying the problem. This value can be passed to the `ErrorString()` function, or compared to one of the constants defined in the `errors` object.

`ErrorColumnNumber`
  Column number at which an error occurred.

`ErrorLineNumber`
  Line number at which an error occurred.

Here is the list of handlers that can be set. To set a handler on an `xmlparser` object o, use `o.handlername = func`. handlername must be taken from the following list, and func must be a callable object accepting the correct number of arguments. The arguments are all strings, unless otherwise stated.

`StartElementHandler` (name, attributes)
  Called for the start of every element. name is a string containing the element name, and attributes is a dictionary mapping attribute names to their values.

`EndElementHandler` (name)
  Called for the end of every element.

`ProcessingInstructionHandler` (target, data)
  Called for every processing instruction.

`CharacterDataHandler` (data)
  Called for character data.

`UnparsedEntityDeclHandler` (entityName, base, systemId, publicId, notationName)
  Called for unparsed (NDATA) entity declarations.

`NotationDeclHandler` (notationName, base, systemId, publicId)
  Called for notation declarations.

`StartNamespaceDeclHandler` (prefix, uri)
  Called when an element contains a namespace declaration.

`EndNamespaceDeclHandler` (prefix)
  Called when the closing tag is reached for an element that contained a namespace declaration.

`CommentHandler` (data)
  Called for comments.

`StartCdataSectionHandler` ()
  Called at the start of a CDATA section.

`EndCdataSectionHandler` ()
  Called at the end of a CDATA section.

`DefaultHandler` (data)
  Called for any characters in the XML document for which no applicable handler has been specified. This means characters that are part of a construct which could be reported, but for which no handler has been supplied.

`DefaultHandlerExpand` (data)
  This is the same as the `DefaultHandler`, but doesn't inhibit expansion of internal entities. The entity reference will not be passed to the default handler.

`NotStandaloneHandler` ()
  Called if the XML document hasn't been declared as being a standalone document.

`ExternalEntityRefHandler` (context, base, systemId, publicId)
  Called for references to external entities.

Subsections

- 13.4.1 Example
- 13.4.2 Expat error constants