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