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