| 1 |
:mod:`!xml.etree.ElementTree` --- The ElementTree XML API |
| 2 |
========================================================= |
| 3 |
|
| 4 |
.. module:: xml.etree.ElementTree |
| 5 |
:synopsis: Implementation of the ElementTree API. |
| 6 |
|
| 7 |
.. moduleauthor:: Fredrik Lundh <[email protected]> |
| 8 |
|
| 9 |
**Source code:** :source:`Lib/xml/etree/ElementTree.py` |
| 10 |
|
| 11 |
-------------- |
| 12 |
|
| 13 |
The :mod:`!xml.etree.ElementTree` module implements a simple and efficient API |
| 14 |
for parsing and creating XML data. |
| 15 |
|
| 16 |
.. versionchanged:: 3.3 |
| 17 |
This module will use a fast implementation whenever available. |
| 18 |
|
| 19 |
.. deprecated:: 3.3 |
| 20 |
The :mod:`!xml.etree.cElementTree` module is deprecated. |
| 21 |
|
| 22 |
|
| 23 |
.. note:: |
| 24 |
|
| 25 |
If you need to parse untrusted or unauthenticated data, see |
| 26 |
:ref:`xml-security`. |
| 27 |
|
| 28 |
Tutorial |
| 29 |
-------- |
| 30 |
|
| 31 |
This is a short tutorial for using :mod:`!xml.etree.ElementTree` (``ET`` in |
| 32 |
short). The goal is to demonstrate some of the building blocks and basic |
| 33 |
concepts of the module. |
| 34 |
|
| 35 |
XML tree and elements |
| 36 |
^^^^^^^^^^^^^^^^^^^^^ |
| 37 |
|
| 38 |
XML is an inherently hierarchical data format, and the most natural way to |
| 39 |
represent it is with a tree. ``ET`` has two classes for this purpose - |
| 40 |
:class:`ElementTree` represents the whole XML document as a tree, and |
| 41 |
:class:`Element` represents a single node in this tree. Interactions with |
| 42 |
the whole document (reading and writing to/from files) are usually done |
| 43 |
on the :class:`ElementTree` level. Interactions with a single XML element |
| 44 |
and its sub-elements are done on the :class:`Element` level. |
| 45 |
|
| 46 |
.. _elementtree-parsing-xml: |
| 47 |
|
| 48 |
Parsing XML |
| 49 |
^^^^^^^^^^^ |
| 50 |
|
| 51 |
We'll be using the fictive :file:`country_data.xml` XML document as the sample data for this section: |
| 52 |
|
| 53 |
.. code-block:: xml |
| 54 |
|
| 55 |
<?xml version="1.0"?> |
| 56 |
<data> |
| 57 |
<country name="Liechtenstein"> |
| 58 |
<rank>1</rank> |
| 59 |
<year>2008</year> |
| 60 |
<gdppc>141100</gdppc> |
| 61 |
<neighbor name="Austria" direction="E"/> |
| 62 |
<neighbor name="Switzerland" direction="W"/> |
| 63 |
</country> |
| 64 |
<country name="Singapore"> |
| 65 |
<rank>4</rank> |
| 66 |
<year>2011</year> |
| 67 |
<gdppc>59900</gdppc> |
| 68 |
<neighbor name="Malaysia" direction="N"/> |
| 69 |
</country> |
| 70 |
<country name="Panama"> |
| 71 |
<rank>68</rank> |
| 72 |
<year>2011</year> |
| 73 |
<gdppc>13600</gdppc> |
| 74 |
<neighbor name="Costa Rica" direction="W"/> |
| 75 |
<neighbor name="Colombia" direction="E"/> |
| 76 |
</country> |
| 77 |
</data> |
| 78 |
|
| 79 |
We can import this data by reading from a file:: |
| 80 |
|
| 81 |
import xml.etree.ElementTree as ET |
| 82 |
tree = ET.parse('country_data.xml') |
| 83 |
root = tree.getroot() |
| 84 |
|
| 85 |
Or directly from a string:: |
| 86 |
|
| 87 |
root = ET.fromstring(country_data_as_string) |
| 88 |
|
| 89 |
:func:`fromstring` parses XML from a string directly into an :class:`Element`, |
| 90 |
which is the root element of the parsed tree. Other parsing functions may |
| 91 |
create an :class:`ElementTree`. Check the documentation to be sure. |
| 92 |
|
| 93 |
As an :class:`Element`, ``root`` has a tag and a dictionary of attributes:: |
| 94 |
|
| 95 |
>>> root.tag |
| 96 |
'data' |
| 97 |
>>> root.attrib |
| 98 |
{} |
| 99 |
|
| 100 |
It also has children nodes over which we can iterate:: |
| 101 |
|
| 102 |
>>> for child in root: |
| 103 |
... print(child.tag, child.attrib) |
| 104 |
... |
| 105 |
country {'name': 'Liechtenstein'} |
| 106 |
country {'name': 'Singapore'} |
| 107 |
country {'name': 'Panama'} |
| 108 |
|
| 109 |
Children are nested, and we can access specific child nodes by index:: |
| 110 |
|
| 111 |
>>> root[0][1].text |
| 112 |
'2008' |
| 113 |
|
| 114 |
|
| 115 |
.. note:: |
| 116 |
|
| 117 |
Not all elements of the XML input will end up as elements of the |
| 118 |
parsed tree. Currently, this module skips over any XML comments, |
| 119 |
processing instructions, and document type declarations in the |
| 120 |
input. Nevertheless, trees built using this module's API rather |
| 121 |
than parsing from XML text can have comments and processing |
| 122 |
instructions in them; they will be included when generating XML |
| 123 |
output. A document type declaration may be accessed by passing a |
| 124 |
custom :class:`TreeBuilder` instance to the :class:`XMLParser` |
| 125 |
constructor. |
| 126 |
|
| 127 |
|
| 128 |
.. _elementtree-pull-parsing: |
| 129 |
|
| 130 |
Pull API for non-blocking parsing |
| 131 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 132 |
|
| 133 |
Most parsing functions provided by this module require the whole document |
| 134 |
to be read at once before returning any result. It is possible to use an |
| 135 |
:class:`XMLParser` and feed data into it incrementally, but it is a push API that |
| 136 |
calls methods on a callback target, which is too low-level and inconvenient for |
| 137 |
most needs. Sometimes what the user really wants is to be able to parse XML |
| 138 |
incrementally, without blocking operations, while enjoying the convenience of |
| 139 |
fully constructed :class:`Element` objects. |
| 140 |
|
| 141 |
The most powerful tool for doing this is :class:`XMLPullParser`. It does not |
| 142 |
require a blocking read to obtain the XML data, and is instead fed with data |
| 143 |
incrementally with :meth:`XMLPullParser.feed` calls. To get the parsed XML |
| 144 |
elements, call :meth:`XMLPullParser.read_events`. Here is an example:: |
| 145 |
|
| 146 |
>>> parser = ET.XMLPullParser(['start', 'end']) |
| 147 |
>>> parser.feed('<mytag>sometext') |
| 148 |
>>> list(parser.read_events()) |
| 149 |
[('start', <Element 'mytag' at 0x7fa66db2be58>)] |
| 150 |
>>> parser.feed(' more text</mytag>') |
| 151 |
>>> for event, elem in parser.read_events(): |
| 152 |
... print(event) |
| 153 |
... print(elem.tag, 'text=', elem.text) |
| 154 |
... |
| 155 |
end |
| 156 |
mytag text= sometext more text |
| 157 |
|
| 158 |
The obvious use case is applications that operate in a non-blocking fashion |
| 159 |
where the XML data is being received from a socket or read incrementally from |
| 160 |
some storage device. In such cases, blocking reads are unacceptable. |
| 161 |
|
| 162 |
Because it's so flexible, :class:`XMLPullParser` can be inconvenient to use for |
| 163 |
simpler use-cases. If you don't mind your application blocking on reading XML |
| 164 |
data but would still like to have incremental parsing capabilities, take a look |
| 165 |
at :func:`iterparse`. It can be useful when you're reading a large XML document |
| 166 |
and don't want to hold it wholly in memory. |
| 167 |
|
| 168 |
Where *immediate* feedback through events is wanted, calling method |
| 169 |
:meth:`XMLPullParser.flush` can help reduce delay; |
| 170 |
please make sure to study the related security notes. |
| 171 |
|
| 172 |
|
| 173 |
Finding interesting elements |
| 174 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 175 |
|
| 176 |
:class:`Element` has some useful methods that help iterate recursively over all |
| 177 |
the sub-tree below it (its children, their children, and so on). For example, |
| 178 |
:meth:`Element.iter`:: |
| 179 |
|
| 180 |
>>> for neighbor in root.iter('neighbor'): |
| 181 |
... print(neighbor.attrib) |
| 182 |
... |
| 183 |
{'name': 'Austria', 'direction': 'E'} |
| 184 |
{'name': 'Switzerland', 'direction': 'W'} |
| 185 |
{'name': 'Malaysia', 'direction': 'N'} |
| 186 |
{'name': 'Costa Rica', 'direction': 'W'} |
| 187 |
{'name': 'Colombia', 'direction': 'E'} |
| 188 |
|
| 189 |
:meth:`Element.findall` finds only elements with a tag which are direct |
| 190 |
children of the current element. :meth:`Element.find` finds the *first* child |
| 191 |
with a particular tag, and :attr:`Element.text` accesses the element's text |
| 192 |
content. :meth:`Element.get` accesses the element's attributes:: |
| 193 |
|
| 194 |
>>> for country in root.findall('country'): |
| 195 |
... rank = country.find('rank').text |
| 196 |
... name = country.get('name') |
| 197 |
... print(name, rank) |
| 198 |
... |
| 199 |
Liechtenstein 1 |
| 200 |
Singapore 4 |
| 201 |
Panama 68 |
| 202 |
|
| 203 |
More sophisticated specification of which elements to look for is possible by |
| 204 |
using :ref:`XPath <elementtree-xpath>`. |
| 205 |
|
| 206 |
Modifying an XML File |
| 207 |
^^^^^^^^^^^^^^^^^^^^^ |
| 208 |
|
| 209 |
:class:`ElementTree` provides a simple way to build XML documents and write them to files. |
| 210 |
The :meth:`ElementTree.write` method serves this purpose. |
| 211 |
|
| 212 |
Once created, an :class:`Element` object may be manipulated by directly changing |
| 213 |
its fields (such as :attr:`Element.text`), adding and modifying attributes |
| 214 |
(:meth:`Element.set` method), as well as adding new children (for example |
| 215 |
with :meth:`Element.append`). |
| 216 |
|
| 217 |
Let's say we want to add one to each country's rank, and add an ``updated`` |
| 218 |
attribute to the rank element:: |
| 219 |
|
| 220 |
>>> for rank in root.iter('rank'): |
| 221 |
... new_rank = int(rank.text) + 1 |
| 222 |
... rank.text = str(new_rank) |
| 223 |
... rank.set('updated', 'yes') |
| 224 |
... |
| 225 |
>>> tree.write('output.xml') |
| 226 |
|
| 227 |
Our XML now looks like this: |
| 228 |
|
| 229 |
.. code-block:: xml |
| 230 |
|
| 231 |
<?xml version="1.0"?> |
| 232 |
<data> |
| 233 |
<country name="Liechtenstein"> |
| 234 |
<rank updated="yes">2</rank> |
| 235 |
<year>2008</year> |
| 236 |
<gdppc>141100</gdppc> |
| 237 |
<neighbor name="Austria" direction="E"/> |
| 238 |
<neighbor name="Switzerland" direction="W"/> |
| 239 |
</country> |
| 240 |
<country name="Singapore"> |
| 241 |
<rank updated="yes">5</rank> |
| 242 |
<year>2011</year> |
| 243 |
<gdppc>59900</gdppc> |
| 244 |
<neighbor name="Malaysia" direction="N"/> |
| 245 |
</country> |
| 246 |
<country name="Panama"> |
| 247 |
<rank updated="yes">69</rank> |
| 248 |
<year>2011</year> |
| 249 |
<gdppc>13600</gdppc> |
| 250 |
<neighbor name="Costa Rica" direction="W"/> |
| 251 |
<neighbor name="Colombia" direction="E"/> |
| 252 |
</country> |
| 253 |
</data> |
| 254 |
|
| 255 |
We can remove elements using :meth:`Element.remove`. Let's say we want to |
| 256 |
remove all countries with a rank higher than 50:: |
| 257 |
|
| 258 |
>>> for country in root.findall('country'): |
| 259 |
... # using root.findall() to avoid removal during traversal |
| 260 |
... rank = int(country.find('rank').text) |
| 261 |
... if rank > 50: |
| 262 |
... root.remove(country) |
| 263 |
... |
| 264 |
>>> tree.write('output.xml') |
| 265 |
|
| 266 |
Note that concurrent modification while iterating can lead to problems, |
| 267 |
just like when iterating and modifying Python lists or dicts. |
| 268 |
Therefore, the example first collects all matching elements with |
| 269 |
``root.findall()``, and only then iterates over the list of matches. |
| 270 |
|
| 271 |
Our XML now looks like this: |
| 272 |
|
| 273 |
.. code-block:: xml |
| 274 |
|
| 275 |
<?xml version="1.0"?> |
| 276 |
<data> |
| 277 |
<country name="Liechtenstein"> |
| 278 |
<rank updated="yes">2</rank> |
| 279 |
<year>2008</year> |
| 280 |
<gdppc>141100</gdppc> |
| 281 |
<neighbor name="Austria" direction="E"/> |
| 282 |
<neighbor name="Switzerland" direction="W"/> |
| 283 |
</country> |
| 284 |
<country name="Singapore"> |
| 285 |
<rank updated="yes">5</rank> |
| 286 |
<year>2011</year> |
| 287 |
<gdppc>59900</gdppc> |
| 288 |
<neighbor name="Malaysia" direction="N"/> |
| 289 |
</country> |
| 290 |
</data> |
| 291 |
|
| 292 |
Building XML documents |
| 293 |
^^^^^^^^^^^^^^^^^^^^^^ |
| 294 |
|
| 295 |
The :func:`SubElement` function also provides a convenient way to create new |
| 296 |
sub-elements for a given element:: |
| 297 |
|
| 298 |
>>> a = ET.Element('a') |
| 299 |
>>> b = ET.SubElement(a, 'b') |
| 300 |
>>> c = ET.SubElement(a, 'c') |
| 301 |
>>> d = ET.SubElement(c, 'd') |
| 302 |
>>> ET.dump(a) |
| 303 |
<a><b /><c><d /></c></a> |
| 304 |
|
| 305 |
Parsing XML with Namespaces |
| 306 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 307 |
|
| 308 |
If the XML input has `namespaces |
| 309 |
<https://en.wikipedia.org/wiki/XML_namespace>`__, tags and attributes |
| 310 |
with prefixes in the form ``prefix:sometag`` get expanded to |
| 311 |
``{uri}sometag`` where the *prefix* is replaced by the full *URI*. |
| 312 |
Also, if there is a `default namespace |
| 313 |
<https://www.w3.org/TR/xml-names/#defaulting>`__, |
| 314 |
that full URI gets prepended to all of the non-prefixed tags. |
| 315 |
|
| 316 |
Here is an XML example that incorporates two namespaces, one with the |
| 317 |
prefix "fictional" and the other serving as the default namespace: |
| 318 |
|
| 319 |
.. code-block:: xml |
| 320 |
|
| 321 |
<?xml version="1.0"?> |
| 322 |
<actors xmlns:fictional="http://characters.example.com" |
| 323 |
xmlns="http://people.example.com"> |
| 324 |
<actor> |
| 325 |
<name>John Cleese</name> |
| 326 |
<fictional:character>Lancelot</fictional:character> |
| 327 |
<fictional:character>Archie Leach</fictional:character> |
| 328 |
</actor> |
| 329 |
<actor> |
| 330 |
<name>Eric Idle</name> |
| 331 |
<fictional:character>Sir Robin</fictional:character> |
| 332 |
<fictional:character>Gunther</fictional:character> |
| 333 |
<fictional:character>Commander Clement</fictional:character> |
| 334 |
</actor> |
| 335 |
</actors> |
| 336 |
|
| 337 |
One way to search and explore this XML example is to manually add the |
| 338 |
URI to every tag or attribute in the xpath of a |
| 339 |
:meth:`~Element.find` or :meth:`~Element.findall`:: |
| 340 |
|
| 341 |
root = fromstring(xml_text) |
| 342 |
for actor in root.findall('{http://people.example.com}actor'): |
| 343 |
name = actor.find('{http://people.example.com}name') |
| 344 |
print(name.text) |
| 345 |
for char in actor.findall('{http://characters.example.com}character'): |
| 346 |
print(' |-->', char.text) |
| 347 |
|
| 348 |
A better way to search the namespaced XML example is to create a |
| 349 |
dictionary with your own prefixes and use those in the search functions:: |
| 350 |
|
| 351 |
ns = {'real_person': 'http://people.example.com', |
| 352 |
'role': 'http://characters.example.com'} |
| 353 |
|
| 354 |
for actor in root.findall('real_person:actor', ns): |
| 355 |
name = actor.find('real_person:name', ns) |
| 356 |
print(name.text) |
| 357 |
for char in actor.findall('role:character', ns): |
| 358 |
print(' |-->', char.text) |
| 359 |
|
| 360 |
These two approaches both output:: |
| 361 |
|
| 362 |
John Cleese |
| 363 |
|--> Lancelot |
| 364 |
|--> Archie Leach |
| 365 |
Eric Idle |
| 366 |
|--> Sir Robin |
| 367 |
|--> Gunther |
| 368 |
|--> Commander Clement |
| 369 |
|
| 370 |
|
| 371 |
.. _elementtree-xpath: |
| 372 |
|
| 373 |
XPath support |
| 374 |
------------- |
| 375 |
|
| 376 |
This module provides limited support for |
| 377 |
`XPath expressions <https://www.w3.org/TR/xpath>`_ for locating elements in a |
| 378 |
tree. The goal is to support a small subset of the abbreviated syntax; a full |
| 379 |
XPath engine is outside the scope of the module. |
| 380 |
|
| 381 |
Example |
| 382 |
^^^^^^^ |
| 383 |
|
| 384 |
Here's an example that demonstrates some of the XPath capabilities of the |
| 385 |
module. We'll be using the ``countrydata`` XML document from the |
| 386 |
:ref:`Parsing XML <elementtree-parsing-xml>` section:: |
| 387 |
|
| 388 |
import xml.etree.ElementTree as ET |
| 389 |
|
| 390 |
root = ET.fromstring(countrydata) |
| 391 |
|
| 392 |
# Top-level elements |
| 393 |
root.findall(".") |
| 394 |
|
| 395 |
# All 'neighbor' grand-children of 'country' children of the top-level |
| 396 |
# elements |
| 397 |
root.findall("./country/neighbor") |
| 398 |
|
| 399 |
# Nodes with name='Singapore' that have a 'year' child |
| 400 |
root.findall(".//year/..[@name='Singapore']") |
| 401 |
|
| 402 |
# 'year' nodes that are children of nodes with name='Singapore' |
| 403 |
root.findall(".//*[@name='Singapore']/year") |
| 404 |
|
| 405 |
# All 'neighbor' nodes that are the second child of their parent |
| 406 |
root.findall(".//neighbor[2]") |
| 407 |
|
| 408 |
For XML with namespaces, use the usual qualified ``{namespace}tag`` notation:: |
| 409 |
|
| 410 |
# All dublin-core "title" tags in the document |
| 411 |
root.findall(".//{http://purl.org/dc/elements/1.1/}title") |
| 412 |
|
| 413 |
|
| 414 |
Supported XPath syntax |
| 415 |
^^^^^^^^^^^^^^^^^^^^^^ |
| 416 |
|
| 417 |
.. tabularcolumns:: |l|L| |
| 418 |
|
| 419 |
+-----------------------+------------------------------------------------------+ |
| 420 |
| Syntax | Meaning | |
| 421 |
+=======================+======================================================+ |
| 422 |
| ``tag`` | Selects all child elements with the given tag. | |
| 423 |
| | For example, ``spam`` selects all child elements | |
| 424 |
| | named ``spam``, and ``spam/egg`` selects all | |
| 425 |
| | grandchildren named ``egg`` in all children named | |
| 426 |
| | ``spam``. ``{namespace}*`` selects all tags in the | |
| 427 |
| | given namespace, ``{*}spam`` selects tags named | |
| 428 |
| | ``spam`` in any (or no) namespace, and ``{}*`` | |
| 429 |
| | only selects tags that are not in a namespace. | |
| 430 |
| | | |
| 431 |
| | .. versionchanged:: 3.8 | |
| 432 |
| | Support for star-wildcards was added. | |
| 433 |
+-----------------------+------------------------------------------------------+ |
| 434 |
| ``*`` | Selects all child elements, including comments and | |
| 435 |
| | processing instructions. For example, ``*/egg`` | |
| 436 |
| | selects all grandchildren named ``egg``. | |
| 437 |
+-----------------------+------------------------------------------------------+ |
| 438 |
| ``.`` | Selects the current node. This is mostly useful | |
| 439 |
| | at the beginning of the path, to indicate that it's | |
| 440 |
| | a relative path. | |
| 441 |
+-----------------------+------------------------------------------------------+ |
| 442 |
| ``//`` | Selects all subelements, on all levels beneath the | |
| 443 |
| | current element. For example, ``.//egg`` selects | |
| 444 |
| | all ``egg`` elements in the entire tree. | |
| 445 |
+-----------------------+------------------------------------------------------+ |
| 446 |
| ``..`` | Selects the parent element. Returns ``None`` if the | |
| 447 |
| | path attempts to reach the ancestors of the start | |
| 448 |
| | element (the element ``find`` was called on). | |
| 449 |
+-----------------------+------------------------------------------------------+ |
| 450 |
| ``[@attrib]`` | Selects all elements that have the given attribute. | |
| 451 |
+-----------------------+------------------------------------------------------+ |
| 452 |
| ``[@attrib='value']`` | Selects all elements for which the given attribute | |
| 453 |
| | has the given value. The value cannot contain | |
| 454 |
| | quotes. | |
| 455 |
+-----------------------+------------------------------------------------------+ |
| 456 |
| ``[@attrib!='value']``| Selects all elements for which the given attribute | |
| 457 |
| | does not have the given value. The value cannot | |
| 458 |
| | contain quotes. | |
| 459 |
| | | |
| 460 |
| | .. versionadded:: 3.10 | |
| 461 |
+-----------------------+------------------------------------------------------+ |
| 462 |
| ``[tag]`` | Selects all elements that have a child named | |
| 463 |
| | ``tag``. Only immediate children are supported. | |
| 464 |
+-----------------------+------------------------------------------------------+ |
| 465 |
| ``[.='text']`` | Selects all elements whose complete text content, | |
| 466 |
| | including descendants, equals the given ``text``. | |
| 467 |
| | | |
| 468 |
| | .. versionadded:: 3.7 | |
| 469 |
+-----------------------+------------------------------------------------------+ |
| 470 |
| ``[.!='text']`` | Selects all elements whose complete text content, | |
| 471 |
| | including descendants, does not equal the given | |
| 472 |
| | ``text``. | |
| 473 |
| | | |
| 474 |
| | .. versionadded:: 3.10 | |
| 475 |
+-----------------------+------------------------------------------------------+ |
| 476 |
| ``[tag='text']`` | Selects all elements that have a child named | |
| 477 |
| | ``tag`` whose complete text content, including | |
| 478 |
| | descendants, equals the given ``text``. | |
| 479 |
+-----------------------+------------------------------------------------------+ |
| 480 |
| ``[tag!='text']`` | Selects all elements that have a child named | |
| 481 |
| | ``tag`` whose complete text content, including | |
| 482 |
| | descendants, does not equal the given ``text``. | |
| 483 |
| | | |
| 484 |
| | .. versionadded:: 3.10 | |
| 485 |
+-----------------------+------------------------------------------------------+ |
| 486 |
| ``[position]`` | Selects all elements that are located at the given | |
| 487 |
| | position. The position can be either an integer | |
| 488 |
| | (1 is the first position), the expression ``last()`` | |
| 489 |
| | (for the last position), or a position relative to | |
| 490 |
| | the last position (e.g. ``last()-1``). | |
| 491 |
+-----------------------+------------------------------------------------------+ |
| 492 |
|
| 493 |
Predicates (expressions within square brackets) must be preceded by a tag |
| 494 |
name, an asterisk, or another predicate. ``position`` predicates must be |
| 495 |
preceded by a tag name. |
| 496 |
|
| 497 |
Reference |
| 498 |
--------- |
| 499 |
|
| 500 |
.. _elementtree-functions: |
| 501 |
|
| 502 |
Functions |
| 503 |
^^^^^^^^^ |
| 504 |
|
| 505 |
.. function:: canonicalize(xml_data=None, *, out=None, from_file=None, **options) |
| 506 |
|
| 507 |
`C14N 2.0 <https://www.w3.org/TR/xml-c14n2/>`_ transformation function. |
| 508 |
|
| 509 |
Canonicalization is a way to normalise XML output in a way that allows |
| 510 |
byte-by-byte comparisons and digital signatures. It reduces the freedom |
| 511 |
that XML serializers have and instead generates a more constrained XML |
| 512 |
representation. The main restrictions regard the placement of namespace |
| 513 |
declarations, the ordering of attributes, and ignorable whitespace. |
| 514 |
|
| 515 |
This function takes an XML data string (*xml_data*) or a file path or |
| 516 |
file-like object (*from_file*) as input, converts it to the canonical |
| 517 |
form, and writes it out using the *out* file(-like) object, if provided, |
| 518 |
or returns it as a text string if not. The output file receives text, |
| 519 |
not bytes. It should therefore be opened in text mode with ``utf-8`` |
| 520 |
encoding. |
| 521 |
|
| 522 |
Typical uses:: |
| 523 |
|
| 524 |
xml_data = "<root>...</root>" |
| 525 |
print(canonicalize(xml_data)) |
| 526 |
|
| 527 |
with open("c14n_output.xml", mode='w', encoding='utf-8') as out_file: |
| 528 |
canonicalize(xml_data, out=out_file) |
| 529 |
|
| 530 |
with open("c14n_output.xml", mode='w', encoding='utf-8') as out_file: |
| 531 |
canonicalize(from_file="inputfile.xml", out=out_file) |
| 532 |
|
| 533 |
The configuration *options* are as follows: |
| 534 |
|
| 535 |
- *with_comments*: set to true to include comments (default: false) |
| 536 |
- *strip_text*: set to true to strip whitespace before and after text content |
| 537 |
(default: false) |
| 538 |
- *rewrite_prefixes*: set to true to replace namespace prefixes by "n{number}" |
| 539 |
(default: false) |
| 540 |
- *qname_aware_tags*: a set of qname aware tag names in which prefixes |
| 541 |
should be replaced in text content (default: empty) |
| 542 |
- *qname_aware_attrs*: a set of qname aware attribute names in which prefixes |
| 543 |
should be replaced in text content (default: empty) |
| 544 |
- *exclude_attrs*: a set of attribute names that should not be serialised |
| 545 |
- *exclude_tags*: a set of tag names that should not be serialised |
| 546 |
|
| 547 |
In the option list above, "a set" refers to any collection or iterable of |
| 548 |
strings, no ordering is expected. |
| 549 |
|
| 550 |
.. versionadded:: 3.8 |
| 551 |
|
| 552 |
|
| 553 |
.. function:: Comment(text=None) |
| 554 |
|
| 555 |
Comment element factory. This factory function creates a special element |
| 556 |
that will be serialized as an XML comment by the standard serializer. The |
| 557 |
comment string can be either a bytestring or a Unicode string. *text* is a |
| 558 |
string containing the comment string. Returns an element instance |
| 559 |
representing a comment. |
| 560 |
|
| 561 |
Note that :class:`XMLParser` skips over comments in the input |
| 562 |
instead of creating comment objects for them. An :class:`ElementTree` will |
| 563 |
only contain comment nodes if they have been inserted into to |
| 564 |
the tree using one of the :class:`Element` methods. |
| 565 |
|
| 566 |
.. function:: dump(elem) |
| 567 |
|
| 568 |
Writes an element tree or element structure to sys.stdout. This function |
| 569 |
should be used for debugging only. |
| 570 |
|
| 571 |
The exact output format is implementation dependent. In this version, it's |
| 572 |
written as an ordinary XML file. |
| 573 |
|
| 574 |
*elem* is an element tree or an individual element. |
| 575 |
|
| 576 |
.. versionchanged:: 3.8 |
| 577 |
The :func:`dump` function now preserves the attribute order specified |
| 578 |
by the user. |
| 579 |
|
| 580 |
|
| 581 |
.. function:: fromstring(text, parser=None) |
| 582 |
|
| 583 |
Parses an XML section from a string constant. Same as :func:`XML`. *text* |
| 584 |
is a string containing XML data. *parser* is an optional parser instance. |
| 585 |
If not given, the standard :class:`XMLParser` parser is used. |
| 586 |
Returns an :class:`Element` instance. |
| 587 |
|
| 588 |
|
| 589 |
.. function:: fromstringlist(sequence, parser=None) |
| 590 |
|
| 591 |
Parses an XML document from a sequence of string fragments. *sequence* is a |
| 592 |
list or other sequence containing XML data fragments. *parser* is an |
| 593 |
optional parser instance. If not given, the standard :class:`XMLParser` |
| 594 |
parser is used. Returns an :class:`Element` instance. |
| 595 |
|
| 596 |
.. versionadded:: 3.2 |
| 597 |
|
| 598 |
|
| 599 |
.. function:: indent(tree, space=" ", level=0) |
| 600 |
|
| 601 |
Appends whitespace to the subtree to indent the tree visually. |
| 602 |
This can be used to generate pretty-printed XML output. |
| 603 |
*tree* can be an Element or ElementTree. *space* is the whitespace |
| 604 |
string that will be inserted for each indentation level, two space |
| 605 |
characters by default. For indenting partial subtrees inside of an |
| 606 |
already indented tree, pass the initial indentation level as *level*. |
| 607 |
|
| 608 |
.. versionadded:: 3.9 |
| 609 |
|
| 610 |
|
| 611 |
.. function:: iselement(element) |
| 612 |
|
| 613 |
Check if an object appears to be a valid element object. *element* is an |
| 614 |
element instance. Return ``True`` if this is an element object. |
| 615 |
|
| 616 |
|
| 617 |
.. function:: iterparse(source, events=None, parser=None) |
| 618 |
|
| 619 |
Parses an XML section into an element tree incrementally, and reports what's |
| 620 |
going on to the user. *source* is a filename or :term:`file object` |
| 621 |
containing XML data. *events* is a sequence of events to report back. The |
| 622 |
supported events are the strings ``"start"``, ``"end"``, ``"comment"``, |
| 623 |
``"pi"``, ``"start-ns"`` and ``"end-ns"`` |
| 624 |
(the "ns" events are used to get detailed namespace |
| 625 |
information). If *events* is omitted, only ``"end"`` events are reported. |
| 626 |
*parser* is an optional parser instance. If not given, the standard |
| 627 |
:class:`XMLParser` parser is used. *parser* must be a subclass of |
| 628 |
:class:`XMLParser` and can only use the default :class:`TreeBuilder` as a |
| 629 |
target. Returns an :term:`iterator` providing ``(event, elem)`` pairs; |
| 630 |
it has a ``root`` attribute that references the root element of the |
| 631 |
resulting XML tree once *source* is fully read. |
| 632 |
The iterator has the :meth:`!close` method that closes the internal |
| 633 |
file object if *source* is a filename. |
| 634 |
|
| 635 |
Note that while :func:`iterparse` builds the tree incrementally, it issues |
| 636 |
blocking reads on *source* (or the file it names). As such, it's unsuitable |
| 637 |
for applications where blocking reads can't be made. For fully non-blocking |
| 638 |
parsing, see :class:`XMLPullParser`. |
| 639 |
|
| 640 |
.. note:: |
| 641 |
|
| 642 |
:func:`iterparse` only guarantees that it has seen the ">" character of a |
| 643 |
starting tag when it emits a "start" event, so the attributes are defined, |
| 644 |
but the contents of the text and tail attributes are undefined at that |
| 645 |
point. The same applies to the element children; they may or may not be |
| 646 |
present. |
| 647 |
|
| 648 |
If you need a fully populated element, look for "end" events instead. |
| 649 |
|
| 650 |
.. deprecated:: 3.4 |
| 651 |
The *parser* argument. |
| 652 |
|
| 653 |
.. versionchanged:: 3.8 |
| 654 |
The ``comment`` and ``pi`` events were added. |
| 655 |
|
| 656 |
.. versionchanged:: 3.13 |
| 657 |
Added the :meth:`!close` method. |
| 658 |
|
| 659 |
|
| 660 |
.. function:: parse(source, parser=None) |
| 661 |
|
| 662 |
Parses an XML section into an element tree. *source* is a filename or file |
| 663 |
object containing XML data. *parser* is an optional parser instance. If |
| 664 |
not given, the standard :class:`XMLParser` parser is used. Returns an |
| 665 |
:class:`ElementTree` instance. |
| 666 |
|
| 667 |
|
| 668 |
.. function:: ProcessingInstruction(target, text=None) |
| 669 |
|
| 670 |
PI element factory. This factory function creates a special element that |
| 671 |
will be serialized as an XML processing instruction. *target* is a string |
| 672 |
containing the PI target. *text* is a string containing the PI contents, if |
| 673 |
given. Returns an element instance, representing a processing instruction. |
| 674 |
|
| 675 |
Note that :class:`XMLParser` skips over processing instructions |
| 676 |
in the input instead of creating PI objects for them. An |
| 677 |
:class:`ElementTree` will only contain processing instruction nodes if |
| 678 |
they have been inserted into to the tree using one of the |
| 679 |
:class:`Element` methods. |
| 680 |
|
| 681 |
.. function:: register_namespace(prefix, uri) |
| 682 |
|
| 683 |
Registers a namespace prefix. The registry is global, and any existing |
| 684 |
mapping for either the given prefix or the namespace URI will be removed. |
| 685 |
*prefix* is a namespace prefix. *uri* is a namespace uri. Tags and |
| 686 |
attributes in this namespace will be serialized with the given prefix, if at |
| 687 |
all possible. |
| 688 |
|
| 689 |
.. versionadded:: 3.2 |
| 690 |
|
| 691 |
|
| 692 |
.. function:: SubElement(parent, tag, attrib={}, **extra) |
| 693 |
|
| 694 |
Subelement factory. This function creates an element instance, and appends |
| 695 |
it to an existing element. |
| 696 |
|
| 697 |
The element name, attribute names, and attribute values can be either |
| 698 |
bytestrings or Unicode strings. *parent* is the parent element. *tag* is |
| 699 |
the subelement name. *attrib* is an optional dictionary, containing element |
| 700 |
attributes. *extra* contains additional attributes, given as keyword |
| 701 |
arguments. Returns an element instance. |
| 702 |
|
| 703 |
|
| 704 |
.. function:: tostring(element, encoding="us-ascii", method="xml", *, \ |
| 705 |
xml_declaration=None, default_namespace=None, \ |
| 706 |
short_empty_elements=True) |
| 707 |
|
| 708 |
Generates a string representation of an XML element, including all |
| 709 |
subelements. *element* is an :class:`Element` instance. *encoding* [1]_ is |
| 710 |
the output encoding (default is US-ASCII). Use ``encoding="unicode"`` to |
| 711 |
generate a Unicode string (otherwise, a bytestring is generated). *method* |
| 712 |
is either ``"xml"``, ``"html"`` or ``"text"`` (default is ``"xml"``). |
| 713 |
*xml_declaration*, *default_namespace* and *short_empty_elements* has the same |
| 714 |
meaning as in :meth:`ElementTree.write`. Returns an (optionally) encoded string |
| 715 |
containing the XML data. |
| 716 |
|
| 717 |
.. versionchanged:: 3.4 |
| 718 |
Added the *short_empty_elements* parameter. |
| 719 |
|
| 720 |
.. versionchanged:: 3.8 |
| 721 |
Added the *xml_declaration* and *default_namespace* parameters. |
| 722 |
|
| 723 |
.. versionchanged:: 3.8 |
| 724 |
The :func:`tostring` function now preserves the attribute order |
| 725 |
specified by the user. |
| 726 |
|
| 727 |
|
| 728 |
.. function:: tostringlist(element, encoding="us-ascii", method="xml", *, \ |
| 729 |
xml_declaration=None, default_namespace=None, \ |
| 730 |
short_empty_elements=True) |
| 731 |
|
| 732 |
Generates a string representation of an XML element, including all |
| 733 |
subelements. *element* is an :class:`Element` instance. *encoding* [1]_ is |
| 734 |
the output encoding (default is US-ASCII). Use ``encoding="unicode"`` to |
| 735 |
generate a Unicode string (otherwise, a bytestring is generated). *method* |
| 736 |
is either ``"xml"``, ``"html"`` or ``"text"`` (default is ``"xml"``). |
| 737 |
*xml_declaration*, *default_namespace* and *short_empty_elements* has the same |
| 738 |
meaning as in :meth:`ElementTree.write`. Returns a list of (optionally) encoded |
| 739 |
strings containing the XML data. It does not guarantee any specific sequence, |
| 740 |
except that ``b"".join(tostringlist(element)) == tostring(element)``. |
| 741 |
|
| 742 |
.. versionadded:: 3.2 |
| 743 |
|
| 744 |
.. versionchanged:: 3.4 |
| 745 |
Added the *short_empty_elements* parameter. |
| 746 |
|
| 747 |
.. versionchanged:: 3.8 |
| 748 |
Added the *xml_declaration* and *default_namespace* parameters. |
| 749 |
|
| 750 |
.. versionchanged:: 3.8 |
| 751 |
The :func:`tostringlist` function now preserves the attribute order |
| 752 |
specified by the user. |
| 753 |
|
| 754 |
|
| 755 |
.. function:: XML(text, parser=None) |
| 756 |
|
| 757 |
Parses an XML section from a string constant. This function can be used to |
| 758 |
embed "XML literals" in Python code. *text* is a string containing XML |
| 759 |
data. *parser* is an optional parser instance. If not given, the standard |
| 760 |
:class:`XMLParser` parser is used. Returns an :class:`Element` instance. |
| 761 |
|
| 762 |
|
| 763 |
.. function:: XMLID(text, parser=None) |
| 764 |
|
| 765 |
Parses an XML section from a string constant, and also returns a dictionary |
| 766 |
which maps from element id:s to elements. *text* is a string containing XML |
| 767 |
data. *parser* is an optional parser instance. If not given, the standard |
| 768 |
:class:`XMLParser` parser is used. Returns a tuple containing an |
| 769 |
:class:`Element` instance and a dictionary. |
| 770 |
|
| 771 |
|
| 772 |
.. _elementtree-xinclude: |
| 773 |
|
| 774 |
XInclude support |
| 775 |
---------------- |
| 776 |
|
| 777 |
This module provides limited support for |
| 778 |
`XInclude directives <https://www.w3.org/TR/xinclude/>`_, via the :mod:`xml.etree.ElementInclude` helper module. This module can be used to insert subtrees and text strings into element trees, based on information in the tree. |
| 779 |
|
| 780 |
Example |
| 781 |
^^^^^^^ |
| 782 |
|
| 783 |
Here's an example that demonstrates use of the XInclude module. To include an XML document in the current document, use the ``{http://www.w3.org/2001/XInclude}include`` element and set the **parse** attribute to ``"xml"``, and use the **href** attribute to specify the document to include. |
| 784 |
|
| 785 |
.. code-block:: xml |
| 786 |
|
| 787 |
<?xml version="1.0"?> |
| 788 |
<document xmlns:xi="http://www.w3.org/2001/XInclude"> |
| 789 |
<xi:include href="source.xml" parse="xml" /> |
| 790 |
</document> |
| 791 |
|
| 792 |
By default, the **href** attribute is treated as a file name. You can use custom loaders to override this behaviour. Also note that the standard helper does not support XPointer syntax. |
| 793 |
|
| 794 |
To process this file, load it as usual, and pass the root element to the :mod:`!xml.etree.ElementTree` module: |
| 795 |
|
| 796 |
.. code-block:: python |
| 797 |
|
| 798 |
from xml.etree import ElementTree, ElementInclude |
| 799 |
|
| 800 |
tree = ElementTree.parse("document.xml") |
| 801 |
root = tree.getroot() |
| 802 |
|
| 803 |
ElementInclude.include(root) |
| 804 |
|
| 805 |
The ElementInclude module replaces the ``{http://www.w3.org/2001/XInclude}include`` element with the root element from the **source.xml** document. The result might look something like this: |
| 806 |
|
| 807 |
.. code-block:: xml |
| 808 |
|
| 809 |
<document xmlns:xi="http://www.w3.org/2001/XInclude"> |
| 810 |
<para>This is a paragraph.</para> |
| 811 |
</document> |
| 812 |
|
| 813 |
If the **parse** attribute is omitted, it defaults to "xml". The href attribute is required. |
| 814 |
|
| 815 |
To include a text document, use the ``{http://www.w3.org/2001/XInclude}include`` element, and set the **parse** attribute to "text": |
| 816 |
|
| 817 |
.. code-block:: xml |
| 818 |
|
| 819 |
<?xml version="1.0"?> |
| 820 |
<document xmlns:xi="http://www.w3.org/2001/XInclude"> |
| 821 |
Copyright (c) <xi:include href="year.txt" parse="text" />. |
| 822 |
</document> |
| 823 |
|
| 824 |
The result might look something like: |
| 825 |
|
| 826 |
.. code-block:: xml |
| 827 |
|
| 828 |
<document xmlns:xi="http://www.w3.org/2001/XInclude"> |
| 829 |
Copyright (c) 2003. |
| 830 |
</document> |
| 831 |
|
| 832 |
Reference |
| 833 |
--------- |
| 834 |
|
| 835 |
.. _elementinclude-functions: |
| 836 |
|
| 837 |
Functions |
| 838 |
^^^^^^^^^ |
| 839 |
|
| 840 |
.. module:: xml.etree.ElementInclude |
| 841 |
|
| 842 |
.. function:: default_loader(href, parse, encoding=None) |
| 843 |
|
| 844 |
Default loader. This default loader reads an included resource from disk. |
| 845 |
*href* is a URL. *parse* is for parse mode either "xml" or "text". |
| 846 |
*encoding* is an optional text encoding. If not given, encoding is ``utf-8``. |
| 847 |
Returns the expanded resource. |
| 848 |
If the parse mode is ``"xml"``, this is an :class:`~xml.etree.ElementTree.Element` instance. |
| 849 |
If the parse mode is ``"text"``, this is a string. |
| 850 |
If the loader fails, it can return ``None`` or raise an exception. |
| 851 |
|
| 852 |
|
| 853 |
.. function:: include(elem, loader=None, base_url=None, max_depth=6) |
| 854 |
|
| 855 |
This function expands XInclude directives in-place in tree pointed by *elem*. |
| 856 |
*elem* is either the root :class:`~xml.etree.ElementTree.Element` or an |
| 857 |
:class:`~xml.etree.ElementTree.ElementTree` instance to find such element. |
| 858 |
*loader* is an optional resource loader. If omitted, it defaults to :func:`default_loader`. |
| 859 |
If given, it should be a callable that implements the same interface as |
| 860 |
:func:`default_loader`. *base_url* is base URL of the original file, to resolve |
| 861 |
relative include file references. *max_depth* is the maximum number of recursive |
| 862 |
inclusions. Limited to reduce the risk of malicious content explosion. |
| 863 |
Pass ``None`` to disable the limitation. |
| 864 |
|
| 865 |
.. versionchanged:: 3.9 |
| 866 |
Added the *base_url* and *max_depth* parameters. |
| 867 |
|
| 868 |
|
| 869 |
.. _elementtree-element-objects: |
| 870 |
|
| 871 |
Element Objects |
| 872 |
^^^^^^^^^^^^^^^ |
| 873 |
|
| 874 |
.. module:: xml.etree.ElementTree |
| 875 |
:noindex: |
| 876 |
:no-index: |
| 877 |
|
| 878 |
.. class:: Element(tag, attrib={}, **extra) |
| 879 |
|
| 880 |
Element class. This class defines the Element interface, and provides a |
| 881 |
reference implementation of this interface. |
| 882 |
|
| 883 |
The element name, attribute names, and attribute values can be either |
| 884 |
bytestrings or Unicode strings. *tag* is the element name. *attrib* is |
| 885 |
an optional dictionary, containing element attributes. *extra* contains |
| 886 |
additional attributes, given as keyword arguments. |
| 887 |
|
| 888 |
|
| 889 |
.. attribute:: tag |
| 890 |
|
| 891 |
A string identifying what kind of data this element represents (the |
| 892 |
element type, in other words). |
| 893 |
|
| 894 |
|
| 895 |
.. attribute:: text |
| 896 |
tail |
| 897 |
|
| 898 |
These attributes can be used to hold additional data associated with |
| 899 |
the element. Their values are usually strings but may be any |
| 900 |
application-specific object. If the element is created from |
| 901 |
an XML file, the *text* attribute holds either the text between |
| 902 |
the element's start tag and its first child or end tag, or ``None``, and |
| 903 |
the *tail* attribute holds either the text between the element's |
| 904 |
end tag and the next tag, or ``None``. For the XML data |
| 905 |
|
| 906 |
.. code-block:: xml |
| 907 |
|
| 908 |
<a><b>1<c>2<d/>3</c></b>4</a> |
| 909 |
|
| 910 |
the *a* element has ``None`` for both *text* and *tail* attributes, |
| 911 |
the *b* element has *text* ``"1"`` and *tail* ``"4"``, |
| 912 |
the *c* element has *text* ``"2"`` and *tail* ``None``, |
| 913 |
and the *d* element has *text* ``None`` and *tail* ``"3"``. |
| 914 |
|
| 915 |
To collect the inner text of an element, see :meth:`itertext`, for |
| 916 |
example ``"".join(element.itertext())``. |
| 917 |
|
| 918 |
Applications may store arbitrary objects in these attributes. |
| 919 |
|
| 920 |
|
| 921 |
.. attribute:: attrib |
| 922 |
|
| 923 |
A dictionary containing the element's attributes. Note that while the |
| 924 |
*attrib* value is always a real mutable Python dictionary, an ElementTree |
| 925 |
implementation may choose to use another internal representation, and |
| 926 |
create the dictionary only if someone asks for it. To take advantage of |
| 927 |
such implementations, use the dictionary methods below whenever possible. |
| 928 |
|
| 929 |
The following dictionary-like methods work on the element attributes. |
| 930 |
|
| 931 |
|
| 932 |
.. method:: clear() |
| 933 |
|
| 934 |
Resets an element. This function removes all subelements, clears all |
| 935 |
attributes, and sets the text and tail attributes to ``None``. |
| 936 |
|
| 937 |
|
| 938 |
.. method:: get(key, default=None) |
| 939 |
|
| 940 |
Gets the element attribute named *key*. |
| 941 |
|
| 942 |
Returns the attribute value, or *default* if the attribute was not found. |
| 943 |
|
| 944 |
|
| 945 |
.. method:: items() |
| 946 |
|
| 947 |
Returns the element attributes as a sequence of (name, value) pairs. The |
| 948 |
attributes are returned in an arbitrary order. |
| 949 |
|
| 950 |
|
| 951 |
.. method:: keys() |
| 952 |
|
| 953 |
Returns the elements attribute names as a list. The names are returned |
| 954 |
in an arbitrary order. |
| 955 |
|
| 956 |
|
| 957 |
.. method:: set(key, value) |
| 958 |
|
| 959 |
Set the attribute *key* on the element to *value*. |
| 960 |
|
| 961 |
The following methods work on the element's children (subelements). |
| 962 |
|
| 963 |
|
| 964 |
.. method:: append(subelement) |
| 965 |
|
| 966 |
Adds the element *subelement* to the end of this element's internal list |
| 967 |
of subelements. Raises :exc:`TypeError` if *subelement* is not an |
| 968 |
:class:`Element`. |
| 969 |
|
| 970 |
|
| 971 |
.. method:: extend(subelements) |
| 972 |
|
| 973 |
Appends *subelements* from an iterable of elements. |
| 974 |
Raises :exc:`TypeError` if a subelement is not an :class:`Element`. |
| 975 |
|
| 976 |
.. versionadded:: 3.2 |
| 977 |
|
| 978 |
|
| 979 |
.. method:: find(match, namespaces=None) |
| 980 |
|
| 981 |
Finds the first subelement matching *match*. *match* may be a tag name |
| 982 |
or a :ref:`path <elementtree-xpath>`. Returns an element instance |
| 983 |
or ``None``. *namespaces* is an optional mapping from namespace prefix |
| 984 |
to full name. Pass ``''`` as prefix to move all unprefixed tag names |
| 985 |
in the expression into the given namespace. |
| 986 |
|
| 987 |
|
| 988 |
.. method:: findall(match, namespaces=None) |
| 989 |
|
| 990 |
Finds all matching subelements, by tag name or |
| 991 |
:ref:`path <elementtree-xpath>`. Returns a list containing all matching |
| 992 |
elements in document order. *namespaces* is an optional mapping from |
| 993 |
namespace prefix to full name. Pass ``''`` as prefix to move all |
| 994 |
unprefixed tag names in the expression into the given namespace. |
| 995 |
|
| 996 |
|
| 997 |
.. method:: findtext(match, default=None, namespaces=None) |
| 998 |
|
| 999 |
Finds text for the first subelement matching *match*. *match* may be |
| 1000 |
a tag name or a :ref:`path <elementtree-xpath>`. Returns the text content |
| 1001 |
of the first matching element, or *default* if no element was found. |
| 1002 |
Note that if the matching element has no text content an empty string |
| 1003 |
is returned. *namespaces* is an optional mapping from namespace prefix |
| 1004 |
to full name. Pass ``''`` as prefix to move all unprefixed tag names |
| 1005 |
in the expression into the given namespace. |
| 1006 |
|
| 1007 |
|
| 1008 |
.. method:: insert(index, subelement) |
| 1009 |
|
| 1010 |
Inserts *subelement* at the given position in this element. Raises |
| 1011 |
:exc:`TypeError` if *subelement* is not an :class:`Element`. |
| 1012 |
|
| 1013 |
|
| 1014 |
.. method:: iter(tag=None) |
| 1015 |
|
| 1016 |
Creates a tree :term:`iterator` with the current element as the root. |
| 1017 |
The iterator iterates over this element and all elements below it, in |
| 1018 |
document (depth first) order. If *tag* is not ``None`` or ``'*'``, only |
| 1019 |
elements whose tag equals *tag* are returned from the iterator. If the |
| 1020 |
tree structure is modified during iteration, the result is undefined. |
| 1021 |
|
| 1022 |
.. versionadded:: 3.2 |
| 1023 |
|
| 1024 |
|
| 1025 |
.. method:: iterfind(match, namespaces=None) |
| 1026 |
|
| 1027 |
Finds all matching subelements, by tag name or |
| 1028 |
:ref:`path <elementtree-xpath>`. Returns an iterable yielding all |
| 1029 |
matching elements in document order. *namespaces* is an optional mapping |
| 1030 |
from namespace prefix to full name. |
| 1031 |
|
| 1032 |
|
| 1033 |
.. versionadded:: 3.2 |
| 1034 |
|
| 1035 |
|
| 1036 |
.. method:: itertext() |
| 1037 |
|
| 1038 |
Creates a text iterator. The iterator loops over this element and all |
| 1039 |
subelements, in document order, and returns all inner text. |
| 1040 |
|
| 1041 |
.. versionadded:: 3.2 |
| 1042 |
|
| 1043 |
|
| 1044 |
.. method:: makeelement(tag, attrib) |
| 1045 |
|
| 1046 |
Creates a new element object of the same type as this element. Do not |
| 1047 |
call this method, use the :func:`SubElement` factory function instead. |
| 1048 |
|
| 1049 |
|
| 1050 |
.. method:: remove(subelement) |
| 1051 |
|
| 1052 |
Removes *subelement* from the element. Unlike the find\* methods this |
| 1053 |
method compares elements based on the instance identity, not on tag value |
| 1054 |
or contents. |
| 1055 |
|
| 1056 |
:class:`Element` objects also support the following sequence type methods |
| 1057 |
for working with subelements: :meth:`~object.__delitem__`, |
| 1058 |
:meth:`~object.__getitem__`, :meth:`~object.__setitem__`, |
| 1059 |
:meth:`~object.__len__`. |
| 1060 |
|
| 1061 |
Caution: Elements with no subelements will test as ``False``. In a future |
| 1062 |
release of Python, all elements will test as ``True`` regardless of whether |
| 1063 |
subelements exist. Instead, prefer explicit ``len(elem)`` or |
| 1064 |
``elem is not None`` tests.:: |
| 1065 |
|
| 1066 |
element = root.find('foo') |
| 1067 |
|
| 1068 |
if not element: # careful! |
| 1069 |
print("element not found, or element has no subelements") |
| 1070 |
|
| 1071 |
if element is None: |
| 1072 |
print("element not found") |
| 1073 |
|
| 1074 |
.. versionchanged:: 3.12 |
| 1075 |
Testing the truth value of an Element emits :exc:`DeprecationWarning`. |
| 1076 |
|
| 1077 |
Prior to Python 3.8, the serialisation order of the XML attributes of |
| 1078 |
elements was artificially made predictable by sorting the attributes by |
| 1079 |
their name. Based on the now guaranteed ordering of dicts, this arbitrary |
| 1080 |
reordering was removed in Python 3.8 to preserve the order in which |
| 1081 |
attributes were originally parsed or created by user code. |
| 1082 |
|
| 1083 |
In general, user code should try not to depend on a specific ordering of |
| 1084 |
attributes, given that the `XML Information Set |
| 1085 |
<https://www.w3.org/TR/xml-infoset/>`_ explicitly excludes the attribute |
| 1086 |
order from conveying information. Code should be prepared to deal with |
| 1087 |
any ordering on input. In cases where deterministic XML output is required, |
| 1088 |
e.g. for cryptographic signing or test data sets, canonical serialisation |
| 1089 |
is available with the :func:`canonicalize` function. |
| 1090 |
|
| 1091 |
In cases where canonical output is not applicable but a specific attribute |
| 1092 |
order is still desirable on output, code should aim for creating the |
| 1093 |
attributes directly in the desired order, to avoid perceptual mismatches |
| 1094 |
for readers of the code. In cases where this is difficult to achieve, a |
| 1095 |
recipe like the following can be applied prior to serialisation to enforce |
| 1096 |
an order independently from the Element creation:: |
| 1097 |
|
| 1098 |
def reorder_attributes(root): |
| 1099 |
for el in root.iter(): |
| 1100 |
attrib = el.attrib |
| 1101 |
if len(attrib) > 1: |
| 1102 |
# adjust attribute order, e.g. by sorting |
| 1103 |
attribs = sorted(attrib.items()) |
| 1104 |
attrib.clear() |
| 1105 |
attrib.update(attribs) |
| 1106 |
|
| 1107 |
|
| 1108 |
.. _elementtree-elementtree-objects: |
| 1109 |
|
| 1110 |
ElementTree Objects |
| 1111 |
^^^^^^^^^^^^^^^^^^^ |
| 1112 |
|
| 1113 |
|
| 1114 |
.. class:: ElementTree(element=None, file=None) |
| 1115 |
|
| 1116 |
ElementTree wrapper class. This class represents an entire element |
| 1117 |
hierarchy, and adds some extra support for serialization to and from |
| 1118 |
standard XML. |
| 1119 |
|
| 1120 |
*element* is the root element. The tree is initialized with the contents |
| 1121 |
of the XML *file* if given. |
| 1122 |
|
| 1123 |
|
| 1124 |
.. method:: _setroot(element) |
| 1125 |
|
| 1126 |
Replaces the root element for this tree. This discards the current |
| 1127 |
contents of the tree, and replaces it with the given element. Use with |
| 1128 |
care. *element* is an element instance. |
| 1129 |
|
| 1130 |
|
| 1131 |
.. method:: find(match, namespaces=None) |
| 1132 |
|
| 1133 |
Same as :meth:`Element.find`, starting at the root of the tree. |
| 1134 |
|
| 1135 |
|
| 1136 |
.. method:: findall(match, namespaces=None) |
| 1137 |
|
| 1138 |
Same as :meth:`Element.findall`, starting at the root of the tree. |
| 1139 |
|
| 1140 |
|
| 1141 |
.. method:: findtext(match, default=None, namespaces=None) |
| 1142 |
|
| 1143 |
Same as :meth:`Element.findtext`, starting at the root of the tree. |
| 1144 |
|
| 1145 |
|
| 1146 |
.. method:: getroot() |
| 1147 |
|
| 1148 |
Returns the root element for this tree. |
| 1149 |
|
| 1150 |
|
| 1151 |
.. method:: iter(tag=None) |
| 1152 |
|
| 1153 |
Creates and returns a tree iterator for the root element. The iterator |
| 1154 |
loops over all elements in this tree, in section order. *tag* is the tag |
| 1155 |
to look for (default is to return all elements). |
| 1156 |
|
| 1157 |
|
| 1158 |
.. method:: iterfind(match, namespaces=None) |
| 1159 |
|
| 1160 |
Same as :meth:`Element.iterfind`, starting at the root of the tree. |
| 1161 |
|
| 1162 |
.. versionadded:: 3.2 |
| 1163 |
|
| 1164 |
|
| 1165 |
.. method:: parse(source, parser=None) |
| 1166 |
|
| 1167 |
Loads an external XML section into this element tree. *source* is a file |
| 1168 |
name or :term:`file object`. *parser* is an optional parser instance. |
| 1169 |
If not given, the standard :class:`XMLParser` parser is used. Returns the |
| 1170 |
section root element. |
| 1171 |
|
| 1172 |
|
| 1173 |
.. method:: write(file, encoding="us-ascii", xml_declaration=None, \ |
| 1174 |
default_namespace=None, method="xml", *, \ |
| 1175 |
short_empty_elements=True) |
| 1176 |
|
| 1177 |
Writes the element tree to a file, as XML. *file* is a file name, or a |
| 1178 |
:term:`file object` opened for writing. *encoding* [1]_ is the output |
| 1179 |
encoding (default is US-ASCII). |
| 1180 |
*xml_declaration* controls if an XML declaration should be added to the |
| 1181 |
file. Use ``False`` for never, ``True`` for always, ``None`` |
| 1182 |
for only if not US-ASCII or UTF-8 or Unicode (default is ``None``). |
| 1183 |
*default_namespace* sets the default XML namespace (for "xmlns"). |
| 1184 |
*method* is either ``"xml"``, ``"html"`` or ``"text"`` (default is |
| 1185 |
``"xml"``). |
| 1186 |
The keyword-only *short_empty_elements* parameter controls the formatting |
| 1187 |
of elements that contain no content. If ``True`` (the default), they are |
| 1188 |
emitted as a single self-closed tag, otherwise they are emitted as a pair |
| 1189 |
of start/end tags. |
| 1190 |
|
| 1191 |
The output is either a string (:class:`str`) or binary (:class:`bytes`). |
| 1192 |
This is controlled by the *encoding* argument. If *encoding* is |
| 1193 |
``"unicode"``, the output is a string; otherwise, it's binary. Note that |
| 1194 |
this may conflict with the type of *file* if it's an open |
| 1195 |
:term:`file object`; make sure you do not try to write a string to a |
| 1196 |
binary stream and vice versa. |
| 1197 |
|
| 1198 |
.. versionchanged:: 3.4 |
| 1199 |
Added the *short_empty_elements* parameter. |
| 1200 |
|
| 1201 |
.. versionchanged:: 3.8 |
| 1202 |
The :meth:`write` method now preserves the attribute order specified |
| 1203 |
by the user. |
| 1204 |
|
| 1205 |
|
| 1206 |
This is the XML file that is going to be manipulated:: |
| 1207 |
|
| 1208 |
<html> |
| 1209 |
<head> |
| 1210 |
<title>Example page</title> |
| 1211 |
</head> |
| 1212 |
<body> |
| 1213 |
<p>Moved to <a href="http://example.org/">example.org</a> |
| 1214 |
or <a href="http://example.com/">example.com</a>.</p> |
| 1215 |
</body> |
| 1216 |
</html> |
| 1217 |
|
| 1218 |
Example of changing the attribute "target" of every link in first paragraph:: |
| 1219 |
|
| 1220 |
>>> from xml.etree.ElementTree import ElementTree |
| 1221 |
>>> tree = ElementTree() |
| 1222 |
>>> tree.parse("index.xhtml") |
| 1223 |
<Element 'html' at 0xb77e6fac> |
| 1224 |
>>> p = tree.find("body/p") # Finds first occurrence of tag p in body |
| 1225 |
>>> p |
| 1226 |
<Element 'p' at 0xb77ec26c> |
| 1227 |
>>> links = list(p.iter("a")) # Returns list of all links |
| 1228 |
>>> links |
| 1229 |
[<Element 'a' at 0xb77ec2ac>, <Element 'a' at 0xb77ec1cc>] |
| 1230 |
>>> for i in links: # Iterates through all found links |
| 1231 |
... i.attrib["target"] = "blank" |
| 1232 |
... |
| 1233 |
>>> tree.write("output.xhtml") |
| 1234 |
|
| 1235 |
.. _elementtree-qname-objects: |
| 1236 |
|
| 1237 |
QName Objects |
| 1238 |
^^^^^^^^^^^^^ |
| 1239 |
|
| 1240 |
|
| 1241 |
.. class:: QName(text_or_uri, tag=None) |
| 1242 |
|
| 1243 |
QName wrapper. This can be used to wrap a QName attribute value, in order |
| 1244 |
to get proper namespace handling on output. *text_or_uri* is a string |
| 1245 |
containing the QName value, in the form {uri}local, or, if the tag argument |
| 1246 |
is given, the URI part of a QName. If *tag* is given, the first argument is |
| 1247 |
interpreted as a URI, and this argument is interpreted as a local name. |
| 1248 |
:class:`QName` instances are opaque. |
| 1249 |
|
| 1250 |
|
| 1251 |
|
| 1252 |
.. _elementtree-treebuilder-objects: |
| 1253 |
|
| 1254 |
TreeBuilder Objects |
| 1255 |
^^^^^^^^^^^^^^^^^^^ |
| 1256 |
|
| 1257 |
|
| 1258 |
.. class:: TreeBuilder(element_factory=None, *, comment_factory=None, \ |
| 1259 |
pi_factory=None, insert_comments=False, insert_pis=False) |
| 1260 |
|
| 1261 |
Generic element structure builder. This builder converts a sequence of |
| 1262 |
start, data, end, comment and pi method calls to a well-formed element |
| 1263 |
structure. You can use this class to build an element structure using |
| 1264 |
a custom XML parser, or a parser for some other XML-like format. |
| 1265 |
|
| 1266 |
*element_factory*, when given, must be a callable accepting two positional |
| 1267 |
arguments: a tag and a dict of attributes. It is expected to return a new |
| 1268 |
element instance. |
| 1269 |
|
| 1270 |
The *comment_factory* and *pi_factory* functions, when given, should behave |
| 1271 |
like the :func:`Comment` and :func:`ProcessingInstruction` functions to |
| 1272 |
create comments and processing instructions. When not given, the default |
| 1273 |
factories will be used. When *insert_comments* and/or *insert_pis* is true, |
| 1274 |
comments/pis will be inserted into the tree if they appear within the root |
| 1275 |
element (but not outside of it). |
| 1276 |
|
| 1277 |
.. method:: close() |
| 1278 |
|
| 1279 |
Flushes the builder buffers, and returns the toplevel document |
| 1280 |
element. Returns an :class:`Element` instance. |
| 1281 |
|
| 1282 |
|
| 1283 |
.. method:: data(data) |
| 1284 |
|
| 1285 |
Adds text to the current element. *data* is a string. This should be |
| 1286 |
either a bytestring, or a Unicode string. |
| 1287 |
|
| 1288 |
|
| 1289 |
.. method:: end(tag) |
| 1290 |
|
| 1291 |
Closes the current element. *tag* is the element name. Returns the |
| 1292 |
closed element. |
| 1293 |
|
| 1294 |
|
| 1295 |
.. method:: start(tag, attrs) |
| 1296 |
|
| 1297 |
Opens a new element. *tag* is the element name. *attrs* is a dictionary |
| 1298 |
containing element attributes. Returns the opened element. |
| 1299 |
|
| 1300 |
|
| 1301 |
.. method:: comment(text) |
| 1302 |
|
| 1303 |
Creates a comment with the given *text*. If ``insert_comments`` is true, |
| 1304 |
this will also add it to the tree. |
| 1305 |
|
| 1306 |
.. versionadded:: 3.8 |
| 1307 |
|
| 1308 |
|
| 1309 |
.. method:: pi(target, text) |
| 1310 |
|
| 1311 |
Creates a process instruction with the given *target* name and *text*. |
| 1312 |
If ``insert_pis`` is true, this will also add it to the tree. |
| 1313 |
|
| 1314 |
.. versionadded:: 3.8 |
| 1315 |
|
| 1316 |
|
| 1317 |
In addition, a custom :class:`TreeBuilder` object can provide the |
| 1318 |
following methods: |
| 1319 |
|
| 1320 |
.. method:: doctype(name, pubid, system) |
| 1321 |
|
| 1322 |
Handles a doctype declaration. *name* is the doctype name. *pubid* is |
| 1323 |
the public identifier. *system* is the system identifier. This method |
| 1324 |
does not exist on the default :class:`TreeBuilder` class. |
| 1325 |
|
| 1326 |
.. versionadded:: 3.2 |
| 1327 |
|
| 1328 |
.. method:: start_ns(prefix, uri) |
| 1329 |
|
| 1330 |
Is called whenever the parser encounters a new namespace declaration, |
| 1331 |
before the ``start()`` callback for the opening element that defines it. |
| 1332 |
*prefix* is ``''`` for the default namespace and the declared |
| 1333 |
namespace prefix name otherwise. *uri* is the namespace URI. |
| 1334 |
|
| 1335 |
.. versionadded:: 3.8 |
| 1336 |
|
| 1337 |
.. method:: end_ns(prefix) |
| 1338 |
|
| 1339 |
Is called after the ``end()`` callback of an element that declared |
| 1340 |
a namespace prefix mapping, with the name of the *prefix* that went |
| 1341 |
out of scope. |
| 1342 |
|
| 1343 |
.. versionadded:: 3.8 |
| 1344 |
|
| 1345 |
|
| 1346 |
.. class:: C14NWriterTarget(write, *, \ |
| 1347 |
with_comments=False, strip_text=False, rewrite_prefixes=False, \ |
| 1348 |
qname_aware_tags=None, qname_aware_attrs=None, \ |
| 1349 |
exclude_attrs=None, exclude_tags=None) |
| 1350 |
|
| 1351 |
A `C14N 2.0 <https://www.w3.org/TR/xml-c14n2/>`_ writer. Arguments are the |
| 1352 |
same as for the :func:`canonicalize` function. This class does not build a |
| 1353 |
tree but translates the callback events directly into a serialised form |
| 1354 |
using the *write* function. |
| 1355 |
|
| 1356 |
.. versionadded:: 3.8 |
| 1357 |
|
| 1358 |
|
| 1359 |
.. _elementtree-xmlparser-objects: |
| 1360 |
|
| 1361 |
XMLParser Objects |
| 1362 |
^^^^^^^^^^^^^^^^^ |
| 1363 |
|
| 1364 |
|
| 1365 |
.. class:: XMLParser(*, target=None, encoding=None) |
| 1366 |
|
| 1367 |
This class is the low-level building block of the module. It uses |
| 1368 |
:mod:`xml.parsers.expat` for efficient, event-based parsing of XML. It can |
| 1369 |
be fed XML data incrementally with the :meth:`feed` method, and parsing |
| 1370 |
events are translated to a push API - by invoking callbacks on the *target* |
| 1371 |
object. If *target* is omitted, the standard :class:`TreeBuilder` is used. |
| 1372 |
If *encoding* [1]_ is given, the value overrides the |
| 1373 |
encoding specified in the XML file. |
| 1374 |
|
| 1375 |
.. versionchanged:: 3.8 |
| 1376 |
Parameters are now :ref:`keyword-only <keyword-only_parameter>`. |
| 1377 |
The *html* argument is no longer supported. |
| 1378 |
|
| 1379 |
|
| 1380 |
.. method:: close() |
| 1381 |
|
| 1382 |
Finishes feeding data to the parser. Returns the result of calling the |
| 1383 |
``close()`` method of the *target* passed during construction; by default, |
| 1384 |
this is the toplevel document element. |
| 1385 |
|
| 1386 |
|
| 1387 |
.. method:: feed(data) |
| 1388 |
|
| 1389 |
Feeds data to the parser. *data* is encoded data. |
| 1390 |
|
| 1391 |
|
| 1392 |
.. method:: flush() |
| 1393 |
|
| 1394 |
Triggers parsing of any previously fed unparsed data, which can be |
| 1395 |
used to ensure more immediate feedback, in particular with Expat >=2.6.0. |
| 1396 |
The implementation of :meth:`flush` temporarily disables reparse deferral |
| 1397 |
with Expat (if currently enabled) and triggers a reparse. |
| 1398 |
Disabling reparse deferral has security consequences; please see |
| 1399 |
:meth:`xml.parsers.expat.xmlparser.SetReparseDeferralEnabled` for details. |
| 1400 |
|
| 1401 |
Note that :meth:`flush` has been backported to some prior releases of |
| 1402 |
CPython as a security fix. Check for availability of :meth:`flush` |
| 1403 |
using :func:`hasattr` if used in code running across a variety of Python |
| 1404 |
versions. |
| 1405 |
|
| 1406 |
.. versionadded:: 3.13 |
| 1407 |
|
| 1408 |
|
| 1409 |
:meth:`XMLParser.feed` calls *target*\'s ``start(tag, attrs_dict)`` method |
| 1410 |
for each opening tag, its ``end(tag)`` method for each closing tag, and data |
| 1411 |
is processed by method ``data(data)``. For further supported callback |
| 1412 |
methods, see the :class:`TreeBuilder` class. :meth:`XMLParser.close` calls |
| 1413 |
*target*\'s method ``close()``. :class:`XMLParser` can be used not only for |
| 1414 |
building a tree structure. This is an example of counting the maximum depth |
| 1415 |
of an XML file:: |
| 1416 |
|
| 1417 |
>>> from xml.etree.ElementTree import XMLParser |
| 1418 |
>>> class MaxDepth: # The target object of the parser |
| 1419 |
... maxDepth = 0 |
| 1420 |
... depth = 0 |
| 1421 |
... def start(self, tag, attrib): # Called for each opening tag. |
| 1422 |
... self.depth += 1 |
| 1423 |
... if self.depth > self.maxDepth: |
| 1424 |
... self.maxDepth = self.depth |
| 1425 |
... def end(self, tag): # Called for each closing tag. |
| 1426 |
... self.depth -= 1 |
| 1427 |
... def data(self, data): |
| 1428 |
... pass # We do not need to do anything with data. |
| 1429 |
... def close(self): # Called when all data has been parsed. |
| 1430 |
... return self.maxDepth |
| 1431 |
... |
| 1432 |
>>> target = MaxDepth() |
| 1433 |
>>> parser = XMLParser(target=target) |
| 1434 |
>>> exampleXml = """ |
| 1435 |
... <a> |
| 1436 |
... <b> |
| 1437 |
... </b> |
| 1438 |
... <b> |
| 1439 |
... <c> |
| 1440 |
... <d> |
| 1441 |
... </d> |
| 1442 |
... </c> |
| 1443 |
... </b> |
| 1444 |
... </a>""" |
| 1445 |
>>> parser.feed(exampleXml) |
| 1446 |
>>> parser.close() |
| 1447 |
4 |
| 1448 |
|
| 1449 |
|
| 1450 |
.. _elementtree-xmlpullparser-objects: |
| 1451 |
|
| 1452 |
XMLPullParser Objects |
| 1453 |
^^^^^^^^^^^^^^^^^^^^^ |
| 1454 |
|
| 1455 |
.. class:: XMLPullParser(events=None) |
| 1456 |
|
| 1457 |
A pull parser suitable for non-blocking applications. Its input-side API is |
| 1458 |
similar to that of :class:`XMLParser`, but instead of pushing calls to a |
| 1459 |
callback target, :class:`XMLPullParser` collects an internal list of parsing |
| 1460 |
events and lets the user read from it. *events* is a sequence of events to |
| 1461 |
report back. The supported events are the strings ``"start"``, ``"end"``, |
| 1462 |
``"comment"``, ``"pi"``, ``"start-ns"`` and ``"end-ns"`` (the "ns" events |
| 1463 |
are used to get detailed namespace information). If *events* is omitted, |
| 1464 |
only ``"end"`` events are reported. |
| 1465 |
|
| 1466 |
.. method:: feed(data) |
| 1467 |
|
| 1468 |
Feed the given bytes data to the parser. |
| 1469 |
|
| 1470 |
.. method:: flush() |
| 1471 |
|
| 1472 |
Triggers parsing of any previously fed unparsed data, which can be |
| 1473 |
used to ensure more immediate feedback, in particular with Expat >=2.6.0. |
| 1474 |
The implementation of :meth:`flush` temporarily disables reparse deferral |
| 1475 |
with Expat (if currently enabled) and triggers a reparse. |
| 1476 |
Disabling reparse deferral has security consequences; please see |
| 1477 |
:meth:`xml.parsers.expat.xmlparser.SetReparseDeferralEnabled` for details. |
| 1478 |
|
| 1479 |
Note that :meth:`flush` has been backported to some prior releases of |
| 1480 |
CPython as a security fix. Check for availability of :meth:`flush` |
| 1481 |
using :func:`hasattr` if used in code running across a variety of Python |
| 1482 |
versions. |
| 1483 |
|
| 1484 |
.. versionadded:: 3.13 |
| 1485 |
|
| 1486 |
.. method:: close() |
| 1487 |
|
| 1488 |
Signal the parser that the data stream is terminated. Unlike |
| 1489 |
:meth:`XMLParser.close`, this method always returns :const:`None`. |
| 1490 |
Any events not yet retrieved when the parser is closed can still be |
| 1491 |
read with :meth:`read_events`. |
| 1492 |
|
| 1493 |
.. method:: read_events() |
| 1494 |
|
| 1495 |
Return an iterator over the events which have been encountered in the |
| 1496 |
data fed to the |
| 1497 |
parser. The iterator yields ``(event, elem)`` pairs, where *event* is a |
| 1498 |
string representing the type of event (e.g. ``"end"``) and *elem* is the |
| 1499 |
encountered :class:`Element` object, or other context value as follows. |
| 1500 |
|
| 1501 |
* ``start``, ``end``: the current Element. |
| 1502 |
* ``comment``, ``pi``: the current comment / processing instruction |
| 1503 |
* ``start-ns``: a tuple ``(prefix, uri)`` naming the declared namespace |
| 1504 |
mapping. |
| 1505 |
* ``end-ns``: :const:`None` (this may change in a future version) |
| 1506 |
|
| 1507 |
Events provided in a previous call to :meth:`read_events` will not be |
| 1508 |
yielded again. Events are consumed from the internal queue only when |
| 1509 |
they are retrieved from the iterator, so multiple readers iterating in |
| 1510 |
parallel over iterators obtained from :meth:`read_events` will have |
| 1511 |
unpredictable results. |
| 1512 |
|
| 1513 |
.. note:: |
| 1514 |
|
| 1515 |
:class:`XMLPullParser` only guarantees that it has seen the ">" |
| 1516 |
character of a starting tag when it emits a "start" event, so the |
| 1517 |
attributes are defined, but the contents of the text and tail attributes |
| 1518 |
are undefined at that point. The same applies to the element children; |
| 1519 |
they may or may not be present. |
| 1520 |
|
| 1521 |
If you need a fully populated element, look for "end" events instead. |
| 1522 |
|
| 1523 |
.. versionadded:: 3.4 |
| 1524 |
|
| 1525 |
.. versionchanged:: 3.8 |
| 1526 |
The ``comment`` and ``pi`` events were added. |
| 1527 |
|
| 1528 |
|
| 1529 |
Exceptions |
| 1530 |
^^^^^^^^^^ |
| 1531 |
|
| 1532 |
.. class:: ParseError |
| 1533 |
|
| 1534 |
XML parse error, raised by the various parsing methods in this module when |
| 1535 |
parsing fails. The string representation of an instance of this exception |
| 1536 |
will contain a user-friendly error message. In addition, it will have |
| 1537 |
the following attributes available: |
| 1538 |
|
| 1539 |
.. attribute:: code |
| 1540 |
|
| 1541 |
A numeric error code from the expat parser. See the documentation of |
| 1542 |
:mod:`xml.parsers.expat` for the list of error codes and their meanings. |
| 1543 |
|
| 1544 |
.. attribute:: position |
| 1545 |
|
| 1546 |
A tuple of *line*, *column* numbers, specifying where the error occurred. |
| 1547 |
|
| 1548 |
.. rubric:: Footnotes |
| 1549 |
|
| 1550 |
.. [1] The encoding string included in XML output should conform to the |
| 1551 |
appropriate standards. For example, "UTF-8" is valid, but "UTF8" is |
| 1552 |
not. See https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl |
| 1553 |
and https://www.iana.org/assignments/character-sets/character-sets.xhtml. |