Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1 | :mod:`xml.parsers.expat` --- Fast XML parsing using Expat |
| 2 | ========================================================= |
| 3 | |
| 4 | .. module:: xml.parsers.expat |
| 5 | :synopsis: An interface to the Expat non-validating XML parser. |
| 6 | .. moduleauthor:: Paul Prescod <paul@prescod.net> |
| 7 | |
| 8 | |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 9 | .. Markup notes: |
| 10 | |
| 11 | Many of the attributes of the XMLParser objects are callbacks. Since |
| 12 | signature information must be presented, these are described using the method |
| 13 | directive. Since they are attributes which are set by client code, in-text |
| 14 | references to these attributes should be marked using the :member: role. |
| 15 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 16 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 17 | .. index:: single: Expat |
| 18 | |
| 19 | The :mod:`xml.parsers.expat` module is a Python interface to the Expat |
| 20 | non-validating XML parser. The module provides a single extension type, |
| 21 | :class:`xmlparser`, that represents the current state of an XML parser. After |
| 22 | an :class:`xmlparser` object has been created, various attributes of the object |
| 23 | can be set to handler functions. When an XML document is then fed to the |
| 24 | parser, the handler functions are called for the character data and markup in |
| 25 | the XML document. |
| 26 | |
| 27 | .. index:: module: pyexpat |
| 28 | |
| 29 | This module uses the :mod:`pyexpat` module to provide access to the Expat |
| 30 | parser. Direct use of the :mod:`pyexpat` module is deprecated. |
| 31 | |
| 32 | This module provides one exception and one type object: |
| 33 | |
| 34 | |
| 35 | .. exception:: ExpatError |
| 36 | |
| 37 | The exception raised when Expat reports an error. See section |
| 38 | :ref:`expaterror-objects` for more information on interpreting Expat errors. |
| 39 | |
| 40 | |
| 41 | .. exception:: error |
| 42 | |
| 43 | Alias for :exc:`ExpatError`. |
| 44 | |
| 45 | |
| 46 | .. data:: XMLParserType |
| 47 | |
| 48 | The type of the return values from the :func:`ParserCreate` function. |
| 49 | |
| 50 | The :mod:`xml.parsers.expat` module contains two functions: |
| 51 | |
| 52 | |
| 53 | .. function:: ErrorString(errno) |
| 54 | |
| 55 | Returns an explanatory string for a given error number *errno*. |
| 56 | |
| 57 | |
Georg Brandl | 1824415 | 2009-09-02 20:34:52 +0000 | [diff] [blame] | 58 | .. function:: ParserCreate(encoding=None, namespace_separator=None) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 59 | |
| 60 | Creates and returns a new :class:`xmlparser` object. *encoding*, if specified, |
| 61 | must be a string naming the encoding used by the XML data. Expat doesn't |
| 62 | support as many encodings as Python does, and its repertoire of encodings can't |
| 63 | be extended; it supports UTF-8, UTF-16, ISO-8859-1 (Latin1), and ASCII. If |
Christian Heimes | b186d00 | 2008-03-18 15:15:01 +0000 | [diff] [blame] | 64 | *encoding* [1]_ is given it will override the implicit or explicit encoding of the |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 65 | document. |
| 66 | |
| 67 | Expat can optionally do XML namespace processing for you, enabled by providing a |
| 68 | value for *namespace_separator*. The value must be a one-character string; a |
| 69 | :exc:`ValueError` will be raised if the string has an illegal length (``None`` |
| 70 | is considered the same as omission). When namespace processing is enabled, |
| 71 | element type names and attribute names that belong to a namespace will be |
| 72 | expanded. The element name passed to the element handlers |
| 73 | :attr:`StartElementHandler` and :attr:`EndElementHandler` will be the |
| 74 | concatenation of the namespace URI, the namespace separator character, and the |
| 75 | local part of the name. If the namespace separator is a zero byte (``chr(0)``) |
| 76 | then the namespace URI and the local part will be concatenated without any |
| 77 | separator. |
| 78 | |
| 79 | For example, if *namespace_separator* is set to a space character (``' '``) and |
| 80 | the following document is parsed:: |
| 81 | |
| 82 | <?xml version="1.0"?> |
| 83 | <root xmlns = "http://default-namespace.org/" |
| 84 | xmlns:py = "http://www.python.org/ns/"> |
| 85 | <py:elem1 /> |
| 86 | <elem2 xmlns="" /> |
| 87 | </root> |
| 88 | |
| 89 | :attr:`StartElementHandler` will receive the following strings for each |
| 90 | element:: |
| 91 | |
| 92 | http://default-namespace.org/ root |
| 93 | http://www.python.org/ns/ elem1 |
| 94 | elem2 |
| 95 | |
| 96 | |
| 97 | .. seealso:: |
| 98 | |
| 99 | `The Expat XML Parser <http://www.libexpat.org/>`_ |
| 100 | Home page of the Expat project. |
| 101 | |
| 102 | |
| 103 | .. _xmlparser-objects: |
| 104 | |
| 105 | XMLParser Objects |
| 106 | ----------------- |
| 107 | |
| 108 | :class:`xmlparser` objects have the following methods: |
| 109 | |
| 110 | |
| 111 | .. method:: xmlparser.Parse(data[, isfinal]) |
| 112 | |
| 113 | Parses the contents of the string *data*, calling the appropriate handler |
| 114 | functions to process the parsed data. *isfinal* must be true on the final call |
| 115 | to this method. *data* can be the empty string at any time. |
| 116 | |
| 117 | |
| 118 | .. method:: xmlparser.ParseFile(file) |
| 119 | |
| 120 | Parse XML data reading from the object *file*. *file* only needs to provide |
| 121 | the ``read(nbytes)`` method, returning the empty string when there's no more |
| 122 | data. |
| 123 | |
| 124 | |
| 125 | .. method:: xmlparser.SetBase(base) |
| 126 | |
| 127 | Sets the base to be used for resolving relative URIs in system identifiers in |
| 128 | declarations. Resolving relative identifiers is left to the application: this |
| 129 | value will be passed through as the *base* argument to the |
| 130 | :func:`ExternalEntityRefHandler`, :func:`NotationDeclHandler`, and |
| 131 | :func:`UnparsedEntityDeclHandler` functions. |
| 132 | |
| 133 | |
| 134 | .. method:: xmlparser.GetBase() |
| 135 | |
| 136 | Returns a string containing the base set by a previous call to :meth:`SetBase`, |
| 137 | or ``None`` if :meth:`SetBase` hasn't been called. |
| 138 | |
| 139 | |
| 140 | .. method:: xmlparser.GetInputContext() |
| 141 | |
| 142 | Returns the input data that generated the current event as a string. The data is |
| 143 | in the encoding of the entity which contains the text. When called while an |
| 144 | event handler is not active, the return value is ``None``. |
| 145 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 146 | |
| 147 | .. method:: xmlparser.ExternalEntityParserCreate(context[, encoding]) |
| 148 | |
| 149 | Create a "child" parser which can be used to parse an external parsed entity |
| 150 | referred to by content parsed by the parent parser. The *context* parameter |
| 151 | should be the string passed to the :meth:`ExternalEntityRefHandler` handler |
| 152 | function, described below. The child parser is created with the |
| 153 | :attr:`ordered_attributes` and :attr:`specified_attributes` set to the values of |
| 154 | this parser. |
| 155 | |
| 156 | |
| 157 | .. method:: xmlparser.UseForeignDTD([flag]) |
| 158 | |
| 159 | Calling this with a true value for *flag* (the default) will cause Expat to call |
| 160 | the :attr:`ExternalEntityRefHandler` with :const:`None` for all arguments to |
| 161 | allow an alternate DTD to be loaded. If the document does not contain a |
| 162 | document type declaration, the :attr:`ExternalEntityRefHandler` will still be |
| 163 | called, but the :attr:`StartDoctypeDeclHandler` and |
| 164 | :attr:`EndDoctypeDeclHandler` will not be called. |
| 165 | |
| 166 | Passing a false value for *flag* will cancel a previous call that passed a true |
| 167 | value, but otherwise has no effect. |
| 168 | |
| 169 | This method can only be called before the :meth:`Parse` or :meth:`ParseFile` |
| 170 | methods are called; calling it after either of those have been called causes |
| 171 | :exc:`ExpatError` to be raised with the :attr:`code` attribute set to |
| 172 | :const:`errors.XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING`. |
| 173 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 174 | :class:`xmlparser` objects have the following attributes: |
| 175 | |
| 176 | |
| 177 | .. attribute:: xmlparser.buffer_size |
| 178 | |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 179 | The size of the buffer used when :attr:`buffer_text` is true. |
| 180 | A new buffer size can be set by assigning a new integer value |
| 181 | to this attribute. |
Christian Heimes | 2380ac7 | 2008-01-09 00:17:24 +0000 | [diff] [blame] | 182 | When the size is changed, the buffer will be flushed. |
| 183 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 184 | |
| 185 | .. attribute:: xmlparser.buffer_text |
| 186 | |
| 187 | Setting this to true causes the :class:`xmlparser` object to buffer textual |
| 188 | content returned by Expat to avoid multiple calls to the |
| 189 | :meth:`CharacterDataHandler` callback whenever possible. This can improve |
| 190 | performance substantially since Expat normally breaks character data into chunks |
| 191 | at every line ending. This attribute is false by default, and may be changed at |
| 192 | any time. |
| 193 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 194 | |
| 195 | .. attribute:: xmlparser.buffer_used |
| 196 | |
| 197 | If :attr:`buffer_text` is enabled, the number of bytes stored in the buffer. |
| 198 | These bytes represent UTF-8 encoded text. This attribute has no meaningful |
| 199 | interpretation when :attr:`buffer_text` is false. |
| 200 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 201 | |
| 202 | .. attribute:: xmlparser.ordered_attributes |
| 203 | |
| 204 | Setting this attribute to a non-zero integer causes the attributes to be |
| 205 | reported as a list rather than a dictionary. The attributes are presented in |
| 206 | the order found in the document text. For each attribute, two list entries are |
| 207 | presented: the attribute name and the attribute value. (Older versions of this |
| 208 | module also used this format.) By default, this attribute is false; it may be |
| 209 | changed at any time. |
| 210 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 211 | |
| 212 | .. attribute:: xmlparser.specified_attributes |
| 213 | |
| 214 | If set to a non-zero integer, the parser will report only those attributes which |
| 215 | were specified in the document instance and not those which were derived from |
| 216 | attribute declarations. Applications which set this need to be especially |
| 217 | careful to use what additional information is available from the declarations as |
| 218 | needed to comply with the standards for the behavior of XML processors. By |
| 219 | default, this attribute is false; it may be changed at any time. |
| 220 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 221 | |
| 222 | The following attributes contain values relating to the most recent error |
| 223 | encountered by an :class:`xmlparser` object, and will only have correct values |
| 224 | once a call to :meth:`Parse` or :meth:`ParseFile` has raised a |
| 225 | :exc:`xml.parsers.expat.ExpatError` exception. |
| 226 | |
| 227 | |
| 228 | .. attribute:: xmlparser.ErrorByteIndex |
| 229 | |
| 230 | Byte index at which an error occurred. |
| 231 | |
| 232 | |
| 233 | .. attribute:: xmlparser.ErrorCode |
| 234 | |
| 235 | Numeric code specifying the problem. This value can be passed to the |
| 236 | :func:`ErrorString` function, or compared to one of the constants defined in the |
| 237 | ``errors`` object. |
| 238 | |
| 239 | |
| 240 | .. attribute:: xmlparser.ErrorColumnNumber |
| 241 | |
| 242 | Column number at which an error occurred. |
| 243 | |
| 244 | |
| 245 | .. attribute:: xmlparser.ErrorLineNumber |
| 246 | |
| 247 | Line number at which an error occurred. |
| 248 | |
| 249 | The following attributes contain values relating to the current parse location |
| 250 | in an :class:`xmlparser` object. During a callback reporting a parse event they |
| 251 | indicate the location of the first of the sequence of characters that generated |
| 252 | the event. When called outside of a callback, the position indicated will be |
| 253 | just past the last parse event (regardless of whether there was an associated |
| 254 | callback). |
| 255 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 256 | |
| 257 | .. attribute:: xmlparser.CurrentByteIndex |
| 258 | |
| 259 | Current byte index in the parser input. |
| 260 | |
| 261 | |
| 262 | .. attribute:: xmlparser.CurrentColumnNumber |
| 263 | |
| 264 | Current column number in the parser input. |
| 265 | |
| 266 | |
| 267 | .. attribute:: xmlparser.CurrentLineNumber |
| 268 | |
| 269 | Current line number in the parser input. |
| 270 | |
| 271 | Here is the list of handlers that can be set. To set a handler on an |
| 272 | :class:`xmlparser` object *o*, use ``o.handlername = func``. *handlername* must |
| 273 | be taken from the following list, and *func* must be a callable object accepting |
| 274 | the correct number of arguments. The arguments are all strings, unless |
| 275 | otherwise stated. |
| 276 | |
| 277 | |
| 278 | .. method:: xmlparser.XmlDeclHandler(version, encoding, standalone) |
| 279 | |
| 280 | Called when the XML declaration is parsed. The XML declaration is the |
| 281 | (optional) declaration of the applicable version of the XML recommendation, the |
| 282 | encoding of the document text, and an optional "standalone" declaration. |
| 283 | *version* and *encoding* will be strings, and *standalone* will be ``1`` if the |
| 284 | document is declared standalone, ``0`` if it is declared not to be standalone, |
| 285 | or ``-1`` if the standalone clause was omitted. This is only available with |
| 286 | Expat version 1.95.0 or newer. |
| 287 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 288 | |
| 289 | .. method:: xmlparser.StartDoctypeDeclHandler(doctypeName, systemId, publicId, has_internal_subset) |
| 290 | |
| 291 | Called when Expat begins parsing the document type declaration (``<!DOCTYPE |
| 292 | ...``). The *doctypeName* is provided exactly as presented. The *systemId* and |
| 293 | *publicId* parameters give the system and public identifiers if specified, or |
| 294 | ``None`` if omitted. *has_internal_subset* will be true if the document |
| 295 | contains and internal document declaration subset. This requires Expat version |
| 296 | 1.2 or newer. |
| 297 | |
| 298 | |
| 299 | .. method:: xmlparser.EndDoctypeDeclHandler() |
| 300 | |
| 301 | Called when Expat is done parsing the document type declaration. This requires |
| 302 | Expat version 1.2 or newer. |
| 303 | |
| 304 | |
| 305 | .. method:: xmlparser.ElementDeclHandler(name, model) |
| 306 | |
| 307 | Called once for each element type declaration. *name* is the name of the |
| 308 | element type, and *model* is a representation of the content model. |
| 309 | |
| 310 | |
| 311 | .. method:: xmlparser.AttlistDeclHandler(elname, attname, type, default, required) |
| 312 | |
| 313 | Called for each declared attribute for an element type. If an attribute list |
| 314 | declaration declares three attributes, this handler is called three times, once |
| 315 | for each attribute. *elname* is the name of the element to which the |
| 316 | declaration applies and *attname* is the name of the attribute declared. The |
| 317 | attribute type is a string passed as *type*; the possible values are |
| 318 | ``'CDATA'``, ``'ID'``, ``'IDREF'``, ... *default* gives the default value for |
| 319 | the attribute used when the attribute is not specified by the document instance, |
| 320 | or ``None`` if there is no default value (``#IMPLIED`` values). If the |
| 321 | attribute is required to be given in the document instance, *required* will be |
| 322 | true. This requires Expat version 1.95.0 or newer. |
| 323 | |
| 324 | |
| 325 | .. method:: xmlparser.StartElementHandler(name, attributes) |
| 326 | |
| 327 | Called for the start of every element. *name* is a string containing the |
| 328 | element name, and *attributes* is a dictionary mapping attribute names to their |
| 329 | values. |
| 330 | |
| 331 | |
| 332 | .. method:: xmlparser.EndElementHandler(name) |
| 333 | |
| 334 | Called for the end of every element. |
| 335 | |
| 336 | |
| 337 | .. method:: xmlparser.ProcessingInstructionHandler(target, data) |
| 338 | |
| 339 | Called for every processing instruction. |
| 340 | |
| 341 | |
| 342 | .. method:: xmlparser.CharacterDataHandler(data) |
| 343 | |
| 344 | Called for character data. This will be called for normal character data, CDATA |
| 345 | marked content, and ignorable whitespace. Applications which must distinguish |
| 346 | these cases can use the :attr:`StartCdataSectionHandler`, |
| 347 | :attr:`EndCdataSectionHandler`, and :attr:`ElementDeclHandler` callbacks to |
| 348 | collect the required information. |
| 349 | |
| 350 | |
| 351 | .. method:: xmlparser.UnparsedEntityDeclHandler(entityName, base, systemId, publicId, notationName) |
| 352 | |
| 353 | Called for unparsed (NDATA) entity declarations. This is only present for |
| 354 | version 1.2 of the Expat library; for more recent versions, use |
| 355 | :attr:`EntityDeclHandler` instead. (The underlying function in the Expat |
| 356 | library has been declared obsolete.) |
| 357 | |
| 358 | |
| 359 | .. method:: xmlparser.EntityDeclHandler(entityName, is_parameter_entity, value, base, systemId, publicId, notationName) |
| 360 | |
| 361 | Called for all entity declarations. For parameter and internal entities, |
| 362 | *value* will be a string giving the declared contents of the entity; this will |
| 363 | be ``None`` for external entities. The *notationName* parameter will be |
| 364 | ``None`` for parsed entities, and the name of the notation for unparsed |
| 365 | entities. *is_parameter_entity* will be true if the entity is a parameter entity |
| 366 | or false for general entities (most applications only need to be concerned with |
| 367 | general entities). This is only available starting with version 1.95.0 of the |
| 368 | Expat library. |
| 369 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 370 | |
| 371 | .. method:: xmlparser.NotationDeclHandler(notationName, base, systemId, publicId) |
| 372 | |
| 373 | Called for notation declarations. *notationName*, *base*, and *systemId*, and |
| 374 | *publicId* are strings if given. If the public identifier is omitted, |
| 375 | *publicId* will be ``None``. |
| 376 | |
| 377 | |
| 378 | .. method:: xmlparser.StartNamespaceDeclHandler(prefix, uri) |
| 379 | |
| 380 | Called when an element contains a namespace declaration. Namespace declarations |
| 381 | are processed before the :attr:`StartElementHandler` is called for the element |
| 382 | on which declarations are placed. |
| 383 | |
| 384 | |
| 385 | .. method:: xmlparser.EndNamespaceDeclHandler(prefix) |
| 386 | |
| 387 | Called when the closing tag is reached for an element that contained a |
| 388 | namespace declaration. This is called once for each namespace declaration on |
| 389 | the element in the reverse of the order for which the |
| 390 | :attr:`StartNamespaceDeclHandler` was called to indicate the start of each |
| 391 | namespace declaration's scope. Calls to this handler are made after the |
| 392 | corresponding :attr:`EndElementHandler` for the end of the element. |
| 393 | |
| 394 | |
| 395 | .. method:: xmlparser.CommentHandler(data) |
| 396 | |
| 397 | Called for comments. *data* is the text of the comment, excluding the leading |
| 398 | '``<!-``\ ``-``' and trailing '``-``\ ``->``'. |
| 399 | |
| 400 | |
| 401 | .. method:: xmlparser.StartCdataSectionHandler() |
| 402 | |
| 403 | Called at the start of a CDATA section. This and :attr:`EndCdataSectionHandler` |
| 404 | are needed to be able to identify the syntactical start and end for CDATA |
| 405 | sections. |
| 406 | |
| 407 | |
| 408 | .. method:: xmlparser.EndCdataSectionHandler() |
| 409 | |
| 410 | Called at the end of a CDATA section. |
| 411 | |
| 412 | |
| 413 | .. method:: xmlparser.DefaultHandler(data) |
| 414 | |
| 415 | Called for any characters in the XML document for which no applicable handler |
| 416 | has been specified. This means characters that are part of a construct which |
| 417 | could be reported, but for which no handler has been supplied. |
| 418 | |
| 419 | |
| 420 | .. method:: xmlparser.DefaultHandlerExpand(data) |
| 421 | |
| 422 | This is the same as the :func:`DefaultHandler`, but doesn't inhibit expansion |
| 423 | of internal entities. The entity reference will not be passed to the default |
| 424 | handler. |
| 425 | |
| 426 | |
| 427 | .. method:: xmlparser.NotStandaloneHandler() |
| 428 | |
| 429 | Called if the XML document hasn't been declared as being a standalone document. |
| 430 | This happens when there is an external subset or a reference to a parameter |
| 431 | entity, but the XML declaration does not set standalone to ``yes`` in an XML |
| 432 | declaration. If this handler returns ``0``, then the parser will throw an |
| 433 | :const:`XML_ERROR_NOT_STANDALONE` error. If this handler is not set, no |
| 434 | exception is raised by the parser for this condition. |
| 435 | |
| 436 | |
| 437 | .. method:: xmlparser.ExternalEntityRefHandler(context, base, systemId, publicId) |
| 438 | |
| 439 | Called for references to external entities. *base* is the current base, as set |
| 440 | by a previous call to :meth:`SetBase`. The public and system identifiers, |
| 441 | *systemId* and *publicId*, are strings if given; if the public identifier is not |
| 442 | given, *publicId* will be ``None``. The *context* value is opaque and should |
| 443 | only be used as described below. |
| 444 | |
| 445 | For external entities to be parsed, this handler must be implemented. It is |
| 446 | responsible for creating the sub-parser using |
| 447 | ``ExternalEntityParserCreate(context)``, initializing it with the appropriate |
| 448 | callbacks, and parsing the entity. This handler should return an integer; if it |
| 449 | returns ``0``, the parser will throw an |
| 450 | :const:`XML_ERROR_EXTERNAL_ENTITY_HANDLING` error, otherwise parsing will |
| 451 | continue. |
| 452 | |
| 453 | If this handler is not provided, external entities are reported by the |
| 454 | :attr:`DefaultHandler` callback, if provided. |
| 455 | |
| 456 | |
| 457 | .. _expaterror-objects: |
| 458 | |
| 459 | ExpatError Exceptions |
| 460 | --------------------- |
| 461 | |
| 462 | .. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org> |
| 463 | |
| 464 | |
| 465 | :exc:`ExpatError` exceptions have a number of interesting attributes: |
| 466 | |
| 467 | |
| 468 | .. attribute:: ExpatError.code |
| 469 | |
| 470 | Expat's internal error number for the specific error. This will match one of |
| 471 | the constants defined in the ``errors`` object from this module. |
| 472 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 473 | |
| 474 | .. attribute:: ExpatError.lineno |
| 475 | |
| 476 | Line number on which the error was detected. The first line is numbered ``1``. |
| 477 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 478 | |
| 479 | .. attribute:: ExpatError.offset |
| 480 | |
| 481 | Character offset into the line where the error occurred. The first column is |
| 482 | numbered ``0``. |
| 483 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 484 | |
| 485 | .. _expat-example: |
| 486 | |
| 487 | Example |
| 488 | ------- |
| 489 | |
| 490 | The following program defines three handlers that just print out their |
| 491 | arguments. :: |
| 492 | |
| 493 | import xml.parsers.expat |
| 494 | |
| 495 | # 3 handler functions |
| 496 | def start_element(name, attrs): |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 497 | print('Start element:', name, attrs) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 498 | def end_element(name): |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 499 | print('End element:', name) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 500 | def char_data(data): |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 501 | print('Character data:', repr(data)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 502 | |
| 503 | p = xml.parsers.expat.ParserCreate() |
| 504 | |
| 505 | p.StartElementHandler = start_element |
| 506 | p.EndElementHandler = end_element |
| 507 | p.CharacterDataHandler = char_data |
| 508 | |
| 509 | p.Parse("""<?xml version="1.0"?> |
| 510 | <parent id="top"><child1 name="paul">Text goes here</child1> |
| 511 | <child2 name="fred">More text</child2> |
| 512 | </parent>""", 1) |
| 513 | |
| 514 | The output from this program is:: |
| 515 | |
| 516 | Start element: parent {'id': 'top'} |
| 517 | Start element: child1 {'name': 'paul'} |
| 518 | Character data: 'Text goes here' |
| 519 | End element: child1 |
| 520 | Character data: '\n' |
| 521 | Start element: child2 {'name': 'fred'} |
| 522 | Character data: 'More text' |
| 523 | End element: child2 |
| 524 | Character data: '\n' |
| 525 | End element: parent |
| 526 | |
| 527 | |
| 528 | .. _expat-content-models: |
| 529 | |
| 530 | Content Model Descriptions |
| 531 | -------------------------- |
| 532 | |
| 533 | .. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org> |
| 534 | |
| 535 | |
| 536 | Content modules are described using nested tuples. Each tuple contains four |
| 537 | values: the type, the quantifier, the name, and a tuple of children. Children |
| 538 | are simply additional content module descriptions. |
| 539 | |
| 540 | The values of the first two fields are constants defined in the ``model`` object |
| 541 | of the :mod:`xml.parsers.expat` module. These constants can be collected in two |
| 542 | groups: the model type group and the quantifier group. |
| 543 | |
| 544 | The constants in the model type group are: |
| 545 | |
| 546 | |
| 547 | .. data:: XML_CTYPE_ANY |
| 548 | :noindex: |
| 549 | |
| 550 | The element named by the model name was declared to have a content model of |
| 551 | ``ANY``. |
| 552 | |
| 553 | |
| 554 | .. data:: XML_CTYPE_CHOICE |
| 555 | :noindex: |
| 556 | |
| 557 | The named element allows a choice from a number of options; this is used for |
| 558 | content models such as ``(A | B | C)``. |
| 559 | |
| 560 | |
| 561 | .. data:: XML_CTYPE_EMPTY |
| 562 | :noindex: |
| 563 | |
| 564 | Elements which are declared to be ``EMPTY`` have this model type. |
| 565 | |
| 566 | |
| 567 | .. data:: XML_CTYPE_MIXED |
| 568 | :noindex: |
| 569 | |
| 570 | |
| 571 | .. data:: XML_CTYPE_NAME |
| 572 | :noindex: |
| 573 | |
| 574 | |
| 575 | .. data:: XML_CTYPE_SEQ |
| 576 | :noindex: |
| 577 | |
| 578 | Models which represent a series of models which follow one after the other are |
| 579 | indicated with this model type. This is used for models such as ``(A, B, C)``. |
| 580 | |
| 581 | The constants in the quantifier group are: |
| 582 | |
| 583 | |
| 584 | .. data:: XML_CQUANT_NONE |
| 585 | :noindex: |
| 586 | |
| 587 | No modifier is given, so it can appear exactly once, as for ``A``. |
| 588 | |
| 589 | |
| 590 | .. data:: XML_CQUANT_OPT |
| 591 | :noindex: |
| 592 | |
| 593 | The model is optional: it can appear once or not at all, as for ``A?``. |
| 594 | |
| 595 | |
| 596 | .. data:: XML_CQUANT_PLUS |
| 597 | :noindex: |
| 598 | |
| 599 | The model must occur one or more times (like ``A+``). |
| 600 | |
| 601 | |
| 602 | .. data:: XML_CQUANT_REP |
| 603 | :noindex: |
| 604 | |
| 605 | The model must occur zero or more times, as for ``A*``. |
| 606 | |
| 607 | |
| 608 | .. _expat-errors: |
| 609 | |
| 610 | Expat error constants |
| 611 | --------------------- |
| 612 | |
| 613 | The following constants are provided in the ``errors`` object of the |
| 614 | :mod:`xml.parsers.expat` module. These constants are useful in interpreting |
| 615 | some of the attributes of the :exc:`ExpatError` exception objects raised when an |
| 616 | error has occurred. |
| 617 | |
| 618 | The ``errors`` object has the following attributes: |
| 619 | |
| 620 | |
| 621 | .. data:: XML_ERROR_ASYNC_ENTITY |
| 622 | :noindex: |
| 623 | |
| 624 | |
| 625 | .. data:: XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF |
| 626 | :noindex: |
| 627 | |
| 628 | An entity reference in an attribute value referred to an external entity instead |
| 629 | of an internal entity. |
| 630 | |
| 631 | |
| 632 | .. data:: XML_ERROR_BAD_CHAR_REF |
| 633 | :noindex: |
| 634 | |
| 635 | A character reference referred to a character which is illegal in XML (for |
| 636 | example, character ``0``, or '``�``'). |
| 637 | |
| 638 | |
| 639 | .. data:: XML_ERROR_BINARY_ENTITY_REF |
| 640 | :noindex: |
| 641 | |
| 642 | An entity reference referred to an entity which was declared with a notation, so |
| 643 | cannot be parsed. |
| 644 | |
| 645 | |
| 646 | .. data:: XML_ERROR_DUPLICATE_ATTRIBUTE |
| 647 | :noindex: |
| 648 | |
| 649 | An attribute was used more than once in a start tag. |
| 650 | |
| 651 | |
| 652 | .. data:: XML_ERROR_INCORRECT_ENCODING |
| 653 | :noindex: |
| 654 | |
| 655 | |
| 656 | .. data:: XML_ERROR_INVALID_TOKEN |
| 657 | :noindex: |
| 658 | |
| 659 | Raised when an input byte could not properly be assigned to a character; for |
| 660 | example, a NUL byte (value ``0``) in a UTF-8 input stream. |
| 661 | |
| 662 | |
| 663 | .. data:: XML_ERROR_JUNK_AFTER_DOC_ELEMENT |
| 664 | :noindex: |
| 665 | |
| 666 | Something other than whitespace occurred after the document element. |
| 667 | |
| 668 | |
| 669 | .. data:: XML_ERROR_MISPLACED_XML_PI |
| 670 | :noindex: |
| 671 | |
| 672 | An XML declaration was found somewhere other than the start of the input data. |
| 673 | |
| 674 | |
| 675 | .. data:: XML_ERROR_NO_ELEMENTS |
| 676 | :noindex: |
| 677 | |
| 678 | The document contains no elements (XML requires all documents to contain exactly |
| 679 | one top-level element).. |
| 680 | |
| 681 | |
| 682 | .. data:: XML_ERROR_NO_MEMORY |
| 683 | :noindex: |
| 684 | |
| 685 | Expat was not able to allocate memory internally. |
| 686 | |
| 687 | |
| 688 | .. data:: XML_ERROR_PARAM_ENTITY_REF |
| 689 | :noindex: |
| 690 | |
| 691 | A parameter entity reference was found where it was not allowed. |
| 692 | |
| 693 | |
| 694 | .. data:: XML_ERROR_PARTIAL_CHAR |
| 695 | :noindex: |
| 696 | |
| 697 | An incomplete character was found in the input. |
| 698 | |
| 699 | |
| 700 | .. data:: XML_ERROR_RECURSIVE_ENTITY_REF |
| 701 | :noindex: |
| 702 | |
| 703 | An entity reference contained another reference to the same entity; possibly via |
| 704 | a different name, and possibly indirectly. |
| 705 | |
| 706 | |
| 707 | .. data:: XML_ERROR_SYNTAX |
| 708 | :noindex: |
| 709 | |
| 710 | Some unspecified syntax error was encountered. |
| 711 | |
| 712 | |
| 713 | .. data:: XML_ERROR_TAG_MISMATCH |
| 714 | :noindex: |
| 715 | |
| 716 | An end tag did not match the innermost open start tag. |
| 717 | |
| 718 | |
| 719 | .. data:: XML_ERROR_UNCLOSED_TOKEN |
| 720 | :noindex: |
| 721 | |
| 722 | Some token (such as a start tag) was not closed before the end of the stream or |
| 723 | the next token was encountered. |
| 724 | |
| 725 | |
| 726 | .. data:: XML_ERROR_UNDEFINED_ENTITY |
| 727 | :noindex: |
| 728 | |
| 729 | A reference was made to a entity which was not defined. |
| 730 | |
| 731 | |
| 732 | .. data:: XML_ERROR_UNKNOWN_ENCODING |
| 733 | :noindex: |
| 734 | |
| 735 | The document encoding is not supported by Expat. |
| 736 | |
| 737 | |
| 738 | .. data:: XML_ERROR_UNCLOSED_CDATA_SECTION |
| 739 | :noindex: |
| 740 | |
| 741 | A CDATA marked section was not closed. |
| 742 | |
| 743 | |
| 744 | .. data:: XML_ERROR_EXTERNAL_ENTITY_HANDLING |
| 745 | :noindex: |
| 746 | |
| 747 | |
| 748 | .. data:: XML_ERROR_NOT_STANDALONE |
| 749 | :noindex: |
| 750 | |
| 751 | The parser determined that the document was not "standalone" though it declared |
| 752 | itself to be in the XML declaration, and the :attr:`NotStandaloneHandler` was |
| 753 | set and returned ``0``. |
| 754 | |
| 755 | |
| 756 | .. data:: XML_ERROR_UNEXPECTED_STATE |
| 757 | :noindex: |
| 758 | |
| 759 | |
| 760 | .. data:: XML_ERROR_ENTITY_DECLARED_IN_PE |
| 761 | :noindex: |
| 762 | |
| 763 | |
| 764 | .. data:: XML_ERROR_FEATURE_REQUIRES_XML_DTD |
| 765 | :noindex: |
| 766 | |
| 767 | An operation was requested that requires DTD support to be compiled in, but |
| 768 | Expat was configured without DTD support. This should never be reported by a |
| 769 | standard build of the :mod:`xml.parsers.expat` module. |
| 770 | |
| 771 | |
| 772 | .. data:: XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING |
| 773 | :noindex: |
| 774 | |
| 775 | A behavioral change was requested after parsing started that can only be changed |
| 776 | before parsing has started. This is (currently) only raised by |
| 777 | :meth:`UseForeignDTD`. |
| 778 | |
| 779 | |
| 780 | .. data:: XML_ERROR_UNBOUND_PREFIX |
| 781 | :noindex: |
| 782 | |
| 783 | An undeclared prefix was found when namespace processing was enabled. |
| 784 | |
| 785 | |
| 786 | .. data:: XML_ERROR_UNDECLARING_PREFIX |
| 787 | :noindex: |
| 788 | |
| 789 | The document attempted to remove the namespace declaration associated with a |
| 790 | prefix. |
| 791 | |
| 792 | |
| 793 | .. data:: XML_ERROR_INCOMPLETE_PE |
| 794 | :noindex: |
| 795 | |
| 796 | A parameter entity contained incomplete markup. |
| 797 | |
| 798 | |
| 799 | .. data:: XML_ERROR_XML_DECL |
| 800 | :noindex: |
| 801 | |
| 802 | The document contained no document element at all. |
| 803 | |
| 804 | |
| 805 | .. data:: XML_ERROR_TEXT_DECL |
| 806 | :noindex: |
| 807 | |
| 808 | There was an error parsing a text declaration in an external entity. |
| 809 | |
| 810 | |
| 811 | .. data:: XML_ERROR_PUBLICID |
| 812 | :noindex: |
| 813 | |
| 814 | Characters were found in the public id that are not allowed. |
| 815 | |
| 816 | |
| 817 | .. data:: XML_ERROR_SUSPENDED |
| 818 | :noindex: |
| 819 | |
| 820 | The requested operation was made on a suspended parser, but isn't allowed. This |
| 821 | includes attempts to provide additional input or to stop the parser. |
| 822 | |
| 823 | |
| 824 | .. data:: XML_ERROR_NOT_SUSPENDED |
| 825 | :noindex: |
| 826 | |
| 827 | An attempt to resume the parser was made when the parser had not been suspended. |
| 828 | |
| 829 | |
| 830 | .. data:: XML_ERROR_ABORTED |
| 831 | :noindex: |
| 832 | |
| 833 | This should not be reported to Python applications. |
| 834 | |
| 835 | |
| 836 | .. data:: XML_ERROR_FINISHED |
| 837 | :noindex: |
| 838 | |
| 839 | The requested operation was made on a parser which was finished parsing input, |
| 840 | but isn't allowed. This includes attempts to provide additional input or to |
| 841 | stop the parser. |
| 842 | |
| 843 | |
| 844 | .. data:: XML_ERROR_SUSPEND_PE |
| 845 | :noindex: |
| 846 | |
Christian Heimes | b186d00 | 2008-03-18 15:15:01 +0000 | [diff] [blame] | 847 | |
| 848 | .. rubric:: Footnotes |
| 849 | |
| 850 | .. [#] The encoding string included in XML output should conform to the |
| 851 | appropriate standards. For example, "UTF-8" is valid, but "UTF8" is |
| 852 | not. See http://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl |
| 853 | and http://www.iana.org/assignments/character-sets . |
| 854 | |