blob: dc9ebb999781a156ac4373dbe69908f966f58650 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`xml.etree.ElementTree` --- The ElementTree XML API
2========================================================
3
4.. module:: xml.etree.ElementTree
5 :synopsis: Implementation of the ElementTree API.
6.. moduleauthor:: Fredrik Lundh <fredrik@pythonware.com>
7
Raymond Hettinger3029aff2011-02-10 08:09:36 +00008**Source code:** :source:`Lib/xml/etree/ElementTree.py`
9
10--------------
Georg Brandl116aa622007-08-15 14:28:22 +000011
Florent Xiclunaf15351d2010-03-13 23:24:31 +000012The :class:`Element` type is a flexible container object, designed to store
13hierarchical data structures in memory. The type can be described as a cross
14between a list and a dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +000015
Christian Heimes7380a672013-03-26 17:35:55 +010016
17.. warning::
18
19 The :mod:`xml.etree.ElementTree` module is not secure against
20 maliciously constructed data. If you need to parse untrusted or
21 unauthenticated data see :ref:`xml-vulnerabilities`.
22
23
Georg Brandl116aa622007-08-15 14:28:22 +000024Each element has a number of properties associated with it:
25
26* a tag which is a string identifying what kind of data this element represents
27 (the element type, in other words).
28
29* a number of attributes, stored in a Python dictionary.
30
31* a text string.
32
33* an optional tail string.
34
35* a number of child elements, stored in a Python sequence
36
Florent Xiclunaf15351d2010-03-13 23:24:31 +000037To create an element instance, use the :class:`Element` constructor or the
38:func:`SubElement` factory function.
Georg Brandl116aa622007-08-15 14:28:22 +000039
40The :class:`ElementTree` class can be used to wrap an element structure, and
41convert it from and to XML.
42
43A C implementation of this API is available as :mod:`xml.etree.cElementTree`.
44
Christian Heimesd8654cf2007-12-02 15:22:16 +000045See http://effbot.org/zone/element-index.htm for tutorials and links to other
Florent Xiclunaf15351d2010-03-13 23:24:31 +000046docs. Fredrik Lundh's page is also the location of the development version of
47the xml.etree.ElementTree.
48
Ezio Melottif8754a62010-03-21 07:16:43 +000049.. versionchanged:: 3.2
Florent Xiclunaf15351d2010-03-13 23:24:31 +000050 The ElementTree API is updated to 1.3. For more information, see
51 `Introducing ElementTree 1.3
52 <http://effbot.org/zone/elementtree-13-intro.htm>`_.
53
Georg Brandl116aa622007-08-15 14:28:22 +000054
55.. _elementtree-functions:
56
57Functions
58---------
59
60
Georg Brandl7f01a132009-09-16 15:58:14 +000061.. function:: Comment(text=None)
Georg Brandl116aa622007-08-15 14:28:22 +000062
Georg Brandlf6945182008-02-01 11:56:49 +000063 Comment element factory. This factory function creates a special element
Florent Xiclunaf15351d2010-03-13 23:24:31 +000064 that will be serialized as an XML comment by the standard serializer. The
65 comment string can be either a bytestring or a Unicode string. *text* is a
66 string containing the comment string. Returns an element instance
Georg Brandlf6945182008-02-01 11:56:49 +000067 representing a comment.
Georg Brandl116aa622007-08-15 14:28:22 +000068
69
70.. function:: dump(elem)
71
Florent Xiclunaf15351d2010-03-13 23:24:31 +000072 Writes an element tree or element structure to sys.stdout. This function
73 should be used for debugging only.
Georg Brandl116aa622007-08-15 14:28:22 +000074
75 The exact output format is implementation dependent. In this version, it's
76 written as an ordinary XML file.
77
78 *elem* is an element tree or an individual element.
79
80
Georg Brandl116aa622007-08-15 14:28:22 +000081.. function:: fromstring(text)
82
Florent Xiclunadddd5e92010-03-14 01:28:07 +000083 Parses an XML section from a string constant. Same as :func:`XML`. *text*
84 is a string containing XML data. Returns an :class:`Element` instance.
Florent Xiclunaf15351d2010-03-13 23:24:31 +000085
86
87.. function:: fromstringlist(sequence, parser=None)
88
89 Parses an XML document from a sequence of string fragments. *sequence* is a
90 list or other sequence containing XML data fragments. *parser* is an
91 optional parser instance. If not given, the standard :class:`XMLParser`
92 parser is used. Returns an :class:`Element` instance.
93
Ezio Melottif8754a62010-03-21 07:16:43 +000094 .. versionadded:: 3.2
Georg Brandl116aa622007-08-15 14:28:22 +000095
96
97.. function:: iselement(element)
98
Florent Xiclunaf15351d2010-03-13 23:24:31 +000099 Checks if an object appears to be a valid element object. *element* is an
100 element instance. Returns a true value if this is an element object.
Georg Brandl116aa622007-08-15 14:28:22 +0000101
102
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000103.. function:: iterparse(source, events=None, parser=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000104
105 Parses an XML section into an element tree incrementally, and reports what's
Eli Bendersky604c4ff2012-03-16 08:41:30 +0200106 going on to the user. *source* is a filename or :term:`file object`
107 containing XML data. *events* is a list of events to report back. The
108 supported events are the strings ``"start"``, ``"end"``, ``"start-ns"``
109 and ``"end-ns"`` (the "ns" events are used to get detailed namespace
110 information). If *events* is omitted, only ``"end"`` events are reported.
111 *parser* is an optional parser instance. If not given, the standard
Eli Bendersky48c50bf2013-01-24 07:23:34 -0800112 :class:`XMLParser` parser is used. *parser* is not supported by
113 ``cElementTree``. Returns an :term:`iterator` providing ``(event, elem)``
114 pairs.
Georg Brandl116aa622007-08-15 14:28:22 +0000115
Benjamin Peterson75edad02009-01-01 15:05:06 +0000116 .. note::
117
118 :func:`iterparse` only guarantees that it has seen the ">"
119 character of a starting tag when it emits a "start" event, so the
120 attributes are defined, but the contents of the text and tail attributes
121 are undefined at that point. The same applies to the element children;
122 they may or may not be present.
123
124 If you need a fully populated element, look for "end" events instead.
125
Georg Brandl116aa622007-08-15 14:28:22 +0000126
Georg Brandl7f01a132009-09-16 15:58:14 +0000127.. function:: parse(source, parser=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000128
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000129 Parses an XML section into an element tree. *source* is a filename or file
130 object containing XML data. *parser* is an optional parser instance. If
131 not given, the standard :class:`XMLParser` parser is used. Returns an
132 :class:`ElementTree` instance.
Georg Brandl116aa622007-08-15 14:28:22 +0000133
134
Georg Brandl7f01a132009-09-16 15:58:14 +0000135.. function:: ProcessingInstruction(target, text=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000136
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000137 PI element factory. This factory function creates a special element that
138 will be serialized as an XML processing instruction. *target* is a string
139 containing the PI target. *text* is a string containing the PI contents, if
140 given. Returns an element instance, representing a processing instruction.
141
142
143.. function:: register_namespace(prefix, uri)
144
145 Registers a namespace prefix. The registry is global, and any existing
146 mapping for either the given prefix or the namespace URI will be removed.
147 *prefix* is a namespace prefix. *uri* is a namespace uri. Tags and
148 attributes in this namespace will be serialized with the given prefix, if at
149 all possible.
150
Ezio Melottif8754a62010-03-21 07:16:43 +0000151 .. versionadded:: 3.2
Georg Brandl116aa622007-08-15 14:28:22 +0000152
153
Georg Brandl7f01a132009-09-16 15:58:14 +0000154.. function:: SubElement(parent, tag, attrib={}, **extra)
Georg Brandl116aa622007-08-15 14:28:22 +0000155
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000156 Subelement factory. This function creates an element instance, and appends
157 it to an existing element.
Georg Brandl116aa622007-08-15 14:28:22 +0000158
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000159 The element name, attribute names, and attribute values can be either
160 bytestrings or Unicode strings. *parent* is the parent element. *tag* is
161 the subelement name. *attrib* is an optional dictionary, containing element
162 attributes. *extra* contains additional attributes, given as keyword
163 arguments. Returns an element instance.
Georg Brandl116aa622007-08-15 14:28:22 +0000164
165
Florent Xiclunac17f1722010-08-08 19:48:29 +0000166.. function:: tostring(element, encoding="us-ascii", method="xml")
Georg Brandl116aa622007-08-15 14:28:22 +0000167
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000168 Generates a string representation of an XML element, including all
Florent Xiclunadddd5e92010-03-14 01:28:07 +0000169 subelements. *element* is an :class:`Element` instance. *encoding* [1]_ is
Florent Xiclunac17f1722010-08-08 19:48:29 +0000170 the output encoding (default is US-ASCII). Use ``encoding="unicode"`` to
171 generate a Unicode string. *method* is either ``"xml"``,
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000172 ``"html"`` or ``"text"`` (default is ``"xml"``). Returns an (optionally)
173 encoded string containing the XML data.
Georg Brandl116aa622007-08-15 14:28:22 +0000174
175
Florent Xiclunac17f1722010-08-08 19:48:29 +0000176.. function:: tostringlist(element, encoding="us-ascii", method="xml")
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000177
178 Generates a string representation of an XML element, including all
Florent Xiclunadddd5e92010-03-14 01:28:07 +0000179 subelements. *element* is an :class:`Element` instance. *encoding* [1]_ is
Florent Xiclunac17f1722010-08-08 19:48:29 +0000180 the output encoding (default is US-ASCII). Use ``encoding="unicode"`` to
181 generate a Unicode string. *method* is either ``"xml"``,
Florent Xiclunadddd5e92010-03-14 01:28:07 +0000182 ``"html"`` or ``"text"`` (default is ``"xml"``). Returns a list of
183 (optionally) encoded strings containing the XML data. It does not guarantee
184 any specific sequence, except that ``"".join(tostringlist(element)) ==
185 tostring(element)``.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000186
Ezio Melottif8754a62010-03-21 07:16:43 +0000187 .. versionadded:: 3.2
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000188
189
190.. function:: XML(text, parser=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000191
192 Parses an XML section from a string constant. This function can be used to
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000193 embed "XML literals" in Python code. *text* is a string containing XML
194 data. *parser* is an optional parser instance. If not given, the standard
195 :class:`XMLParser` parser is used. Returns an :class:`Element` instance.
Georg Brandl116aa622007-08-15 14:28:22 +0000196
197
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000198.. function:: XMLID(text, parser=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000199
200 Parses an XML section from a string constant, and also returns a dictionary
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000201 which maps from element id:s to elements. *text* is a string containing XML
202 data. *parser* is an optional parser instance. If not given, the standard
203 :class:`XMLParser` parser is used. Returns a tuple containing an
204 :class:`Element` instance and a dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +0000205
206
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000207.. _elementtree-element-objects:
Georg Brandl116aa622007-08-15 14:28:22 +0000208
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000209Element Objects
210---------------
Georg Brandl116aa622007-08-15 14:28:22 +0000211
Georg Brandl116aa622007-08-15 14:28:22 +0000212
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000213.. class:: Element(tag, attrib={}, **extra)
Georg Brandl116aa622007-08-15 14:28:22 +0000214
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000215 Element class. This class defines the Element interface, and provides a
216 reference implementation of this interface.
Georg Brandl116aa622007-08-15 14:28:22 +0000217
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000218 The element name, attribute names, and attribute values can be either
219 bytestrings or Unicode strings. *tag* is the element name. *attrib* is
220 an optional dictionary, containing element attributes. *extra* contains
221 additional attributes, given as keyword arguments.
Georg Brandl116aa622007-08-15 14:28:22 +0000222
223
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000224 .. attribute:: tag
Georg Brandl116aa622007-08-15 14:28:22 +0000225
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000226 A string identifying what kind of data this element represents (the
227 element type, in other words).
Georg Brandl116aa622007-08-15 14:28:22 +0000228
229
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000230 .. attribute:: text
Georg Brandl116aa622007-08-15 14:28:22 +0000231
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000232 The *text* attribute can be used to hold additional data associated with
233 the element. As the name implies this attribute is usually a string but
234 may be any application-specific object. If the element is created from
235 an XML file the attribute will contain any text found between the element
236 tags.
Georg Brandl116aa622007-08-15 14:28:22 +0000237
238
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000239 .. attribute:: tail
Georg Brandl116aa622007-08-15 14:28:22 +0000240
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000241 The *tail* attribute can be used to hold additional data associated with
242 the element. This attribute is usually a string but may be any
243 application-specific object. If the element is created from an XML file
244 the attribute will contain any text found after the element's end tag and
245 before the next tag.
Georg Brandl116aa622007-08-15 14:28:22 +0000246
Georg Brandl116aa622007-08-15 14:28:22 +0000247
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000248 .. attribute:: attrib
Georg Brandl116aa622007-08-15 14:28:22 +0000249
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000250 A dictionary containing the element's attributes. Note that while the
251 *attrib* value is always a real mutable Python dictionary, an ElementTree
252 implementation may choose to use another internal representation, and
253 create the dictionary only if someone asks for it. To take advantage of
254 such implementations, use the dictionary methods below whenever possible.
Georg Brandl116aa622007-08-15 14:28:22 +0000255
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000256 The following dictionary-like methods work on the element attributes.
Georg Brandl116aa622007-08-15 14:28:22 +0000257
258
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000259 .. method:: clear()
Georg Brandl116aa622007-08-15 14:28:22 +0000260
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000261 Resets an element. This function removes all subelements, clears all
262 attributes, and sets the text and tail attributes to None.
Georg Brandl116aa622007-08-15 14:28:22 +0000263
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000264
265 .. method:: get(key, default=None)
266
267 Gets the element attribute named *key*.
268
269 Returns the attribute value, or *default* if the attribute was not found.
270
271
272 .. method:: items()
273
274 Returns the element attributes as a sequence of (name, value) pairs. The
275 attributes are returned in an arbitrary order.
276
277
278 .. method:: keys()
279
280 Returns the elements attribute names as a list. The names are returned
281 in an arbitrary order.
282
283
284 .. method:: set(key, value)
285
286 Set the attribute *key* on the element to *value*.
287
288 The following methods work on the element's children (subelements).
289
290
291 .. method:: append(subelement)
292
293 Adds the element *subelement* to the end of this elements internal list
294 of subelements.
295
296
297 .. method:: extend(subelements)
Georg Brandl116aa622007-08-15 14:28:22 +0000298
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000299 Appends *subelements* from a sequence object with zero or more elements.
300 Raises :exc:`AssertionError` if a subelement is not a valid object.
Georg Brandl116aa622007-08-15 14:28:22 +0000301
Ezio Melottif8754a62010-03-21 07:16:43 +0000302 .. versionadded:: 3.2
Georg Brandl116aa622007-08-15 14:28:22 +0000303
Georg Brandl116aa622007-08-15 14:28:22 +0000304
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000305 .. method:: find(match)
Georg Brandl116aa622007-08-15 14:28:22 +0000306
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000307 Finds the first subelement matching *match*. *match* may be a tag name
308 or path. Returns an element instance or ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000309
Georg Brandl116aa622007-08-15 14:28:22 +0000310
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000311 .. method:: findall(match)
Georg Brandl116aa622007-08-15 14:28:22 +0000312
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000313 Finds all matching subelements, by tag name or path. Returns a list
314 containing all matching elements in document order.
Georg Brandl116aa622007-08-15 14:28:22 +0000315
Georg Brandl116aa622007-08-15 14:28:22 +0000316
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000317 .. method:: findtext(match, default=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000318
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000319 Finds text for the first subelement matching *match*. *match* may be
320 a tag name or path. Returns the text content of the first matching
321 element, or *default* if no element was found. Note that if the matching
322 element has no text content an empty string is returned.
Georg Brandl116aa622007-08-15 14:28:22 +0000323
Georg Brandl116aa622007-08-15 14:28:22 +0000324
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000325 .. method:: getchildren()
Georg Brandl116aa622007-08-15 14:28:22 +0000326
Georg Brandl67b21b72010-08-17 15:07:14 +0000327 .. deprecated:: 3.2
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000328 Use ``list(elem)`` or iteration.
Georg Brandl116aa622007-08-15 14:28:22 +0000329
Georg Brandl116aa622007-08-15 14:28:22 +0000330
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000331 .. method:: getiterator(tag=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000332
Georg Brandl67b21b72010-08-17 15:07:14 +0000333 .. deprecated:: 3.2
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000334 Use method :meth:`Element.iter` instead.
Georg Brandl116aa622007-08-15 14:28:22 +0000335
Georg Brandl116aa622007-08-15 14:28:22 +0000336
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000337 .. method:: insert(index, element)
Georg Brandl116aa622007-08-15 14:28:22 +0000338
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000339 Inserts a subelement at the given position in this element.
Georg Brandl116aa622007-08-15 14:28:22 +0000340
Georg Brandl116aa622007-08-15 14:28:22 +0000341
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000342 .. method:: iter(tag=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000343
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000344 Creates a tree :term:`iterator` with the current element as the root.
345 The iterator iterates over this element and all elements below it, in
346 document (depth first) order. If *tag* is not ``None`` or ``'*'``, only
347 elements whose tag equals *tag* are returned from the iterator. If the
348 tree structure is modified during iteration, the result is undefined.
Georg Brandl116aa622007-08-15 14:28:22 +0000349
Ezio Melotti138fc892011-10-10 00:02:03 +0300350 .. versionadded:: 3.2
351
Georg Brandl116aa622007-08-15 14:28:22 +0000352
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000353 .. method:: iterfind(match)
Georg Brandl116aa622007-08-15 14:28:22 +0000354
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000355 Finds all matching subelements, by tag name or path. Returns an iterable
356 yielding all matching elements in document order.
Georg Brandl116aa622007-08-15 14:28:22 +0000357
Ezio Melottif8754a62010-03-21 07:16:43 +0000358 .. versionadded:: 3.2
Georg Brandl116aa622007-08-15 14:28:22 +0000359
Georg Brandl116aa622007-08-15 14:28:22 +0000360
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000361 .. method:: itertext()
Georg Brandl116aa622007-08-15 14:28:22 +0000362
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000363 Creates a text iterator. The iterator loops over this element and all
364 subelements, in document order, and returns all inner text.
Georg Brandl116aa622007-08-15 14:28:22 +0000365
Ezio Melottif8754a62010-03-21 07:16:43 +0000366 .. versionadded:: 3.2
Georg Brandl116aa622007-08-15 14:28:22 +0000367
368
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000369 .. method:: makeelement(tag, attrib)
Georg Brandl116aa622007-08-15 14:28:22 +0000370
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000371 Creates a new element object of the same type as this element. Do not
372 call this method, use the :func:`SubElement` factory function instead.
Georg Brandl116aa622007-08-15 14:28:22 +0000373
374
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000375 .. method:: remove(subelement)
Georg Brandl116aa622007-08-15 14:28:22 +0000376
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000377 Removes *subelement* from the element. Unlike the find\* methods this
378 method compares elements based on the instance identity, not on tag value
379 or contents.
Georg Brandl116aa622007-08-15 14:28:22 +0000380
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000381 :class:`Element` objects also support the following sequence type methods
382 for working with subelements: :meth:`__delitem__`, :meth:`__getitem__`,
383 :meth:`__setitem__`, :meth:`__len__`.
Georg Brandl116aa622007-08-15 14:28:22 +0000384
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000385 Caution: Elements with no subelements will test as ``False``. This behavior
386 will change in future versions. Use specific ``len(elem)`` or ``elem is
387 None`` test instead. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000388
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000389 element = root.find('foo')
Georg Brandl116aa622007-08-15 14:28:22 +0000390
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000391 if not element: # careful!
392 print("element not found, or element has no subelements")
Georg Brandl116aa622007-08-15 14:28:22 +0000393
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000394 if element is None:
395 print("element not found")
Georg Brandl116aa622007-08-15 14:28:22 +0000396
397
398.. _elementtree-elementtree-objects:
399
400ElementTree Objects
401-------------------
402
403
Georg Brandl7f01a132009-09-16 15:58:14 +0000404.. class:: ElementTree(element=None, file=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000405
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000406 ElementTree wrapper class. This class represents an entire element
407 hierarchy, and adds some extra support for serialization to and from
408 standard XML.
Georg Brandl116aa622007-08-15 14:28:22 +0000409
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000410 *element* is the root element. The tree is initialized with the contents
411 of the XML *file* if given.
Georg Brandl116aa622007-08-15 14:28:22 +0000412
413
Benjamin Petersone41251e2008-04-25 01:59:09 +0000414 .. method:: _setroot(element)
Georg Brandl116aa622007-08-15 14:28:22 +0000415
Benjamin Petersone41251e2008-04-25 01:59:09 +0000416 Replaces the root element for this tree. This discards the current
417 contents of the tree, and replaces it with the given element. Use with
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000418 care. *element* is an element instance.
Georg Brandl116aa622007-08-15 14:28:22 +0000419
420
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000421 .. method:: find(match)
Georg Brandl116aa622007-08-15 14:28:22 +0000422
Eli Bendersky7343cb02013-03-12 06:01:22 -0700423 Same as :meth:`Element.find`, starting at the root of the tree.
Georg Brandl116aa622007-08-15 14:28:22 +0000424
425
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000426 .. method:: findall(match)
Georg Brandl116aa622007-08-15 14:28:22 +0000427
Eli Bendersky7343cb02013-03-12 06:01:22 -0700428 Same as :meth:`Element.findall`, starting at the root of the tree.
Georg Brandl116aa622007-08-15 14:28:22 +0000429
430
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000431 .. method:: findtext(match, default=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000432
Eli Bendersky7343cb02013-03-12 06:01:22 -0700433 Same as :meth:`Element.findtext`, starting at the root of the tree.
Georg Brandl116aa622007-08-15 14:28:22 +0000434
435
Georg Brandl7f01a132009-09-16 15:58:14 +0000436 .. method:: getiterator(tag=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000437
Georg Brandl67b21b72010-08-17 15:07:14 +0000438 .. deprecated:: 3.2
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000439 Use method :meth:`ElementTree.iter` instead.
Georg Brandl116aa622007-08-15 14:28:22 +0000440
441
Benjamin Petersone41251e2008-04-25 01:59:09 +0000442 .. method:: getroot()
Florent Xiclunac17f1722010-08-08 19:48:29 +0000443
Benjamin Petersone41251e2008-04-25 01:59:09 +0000444 Returns the root element for this tree.
Georg Brandl116aa622007-08-15 14:28:22 +0000445
446
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000447 .. method:: iter(tag=None)
448
449 Creates and returns a tree iterator for the root element. The iterator
450 loops over all elements in this tree, in section order. *tag* is the tag
451 to look for (default is to return all elements)
452
453
454 .. method:: iterfind(match)
455
456 Finds all matching subelements, by tag name or path. Same as
457 getroot().iterfind(match). Returns an iterable yielding all matching
458 elements in document order.
459
Ezio Melottif8754a62010-03-21 07:16:43 +0000460 .. versionadded:: 3.2
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000461
462
Georg Brandl7f01a132009-09-16 15:58:14 +0000463 .. method:: parse(source, parser=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000464
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000465 Loads an external XML section into this element tree. *source* is a file
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000466 name or :term:`file object`. *parser* is an optional parser instance.
467 If not given, the standard XMLParser parser is used. Returns the section
Benjamin Petersone41251e2008-04-25 01:59:09 +0000468 root element.
Georg Brandl116aa622007-08-15 14:28:22 +0000469
470
Serhiy Storchaka03530b92013-01-13 21:58:04 +0200471 .. method:: write(file, encoding="us-ascii", xml_declaration=None, \
472 default_namespace=None, method="xml")
Georg Brandl116aa622007-08-15 14:28:22 +0000473
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000474 Writes the element tree to a file, as XML. *file* is a file name, or a
Serhiy Storchaka03530b92013-01-13 21:58:04 +0200475 :term:`file object` opened for writing. *encoding* [1]_ is the output
476 encoding (default is US-ASCII). Use ``encoding="unicode"`` to write a
477 Unicode string. *xml_declaration* controls if an XML declaration
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000478 should be added to the file. Use False for never, True for always, None
Serhiy Storchaka03530b92013-01-13 21:58:04 +0200479 for only if not US-ASCII or UTF-8 or Unicode (default is None).
480 *default_namespace* sets the default XML namespace (for "xmlns").
481 *method* is either ``"xml"``, ``"html"`` or ``"text"`` (default is
482 ``"xml"``). Returns an (optionally) encoded string.
Georg Brandl116aa622007-08-15 14:28:22 +0000483
Christian Heimesd8654cf2007-12-02 15:22:16 +0000484This is the XML file that is going to be manipulated::
485
486 <html>
487 <head>
488 <title>Example page</title>
489 </head>
490 <body>
Georg Brandl48310cd2009-01-03 21:18:54 +0000491 <p>Moved to <a href="http://example.org/">example.org</a>
Christian Heimesd8654cf2007-12-02 15:22:16 +0000492 or <a href="http://example.com/">example.com</a>.</p>
493 </body>
494 </html>
495
496Example of changing the attribute "target" of every link in first paragraph::
497
498 >>> from xml.etree.ElementTree import ElementTree
499 >>> tree = ElementTree()
500 >>> tree.parse("index.xhtml")
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000501 <Element 'html' at 0xb77e6fac>
Christian Heimesd8654cf2007-12-02 15:22:16 +0000502 >>> p = tree.find("body/p") # Finds first occurrence of tag p in body
503 >>> p
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000504 <Element 'p' at 0xb77ec26c>
505 >>> links = list(p.iter("a")) # Returns list of all links
Christian Heimesd8654cf2007-12-02 15:22:16 +0000506 >>> links
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000507 [<Element 'a' at 0xb77ec2ac>, <Element 'a' at 0xb77ec1cc>]
Christian Heimesd8654cf2007-12-02 15:22:16 +0000508 >>> for i in links: # Iterates through all found links
509 ... i.attrib["target"] = "blank"
510 >>> tree.write("output.xhtml")
Georg Brandl116aa622007-08-15 14:28:22 +0000511
512.. _elementtree-qname-objects:
513
514QName Objects
515-------------
516
517
Georg Brandl7f01a132009-09-16 15:58:14 +0000518.. class:: QName(text_or_uri, tag=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000519
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000520 QName wrapper. This can be used to wrap a QName attribute value, in order
521 to get proper namespace handling on output. *text_or_uri* is a string
522 containing the QName value, in the form {uri}local, or, if the tag argument
523 is given, the URI part of a QName. If *tag* is given, the first argument is
524 interpreted as an URI, and this argument is interpreted as a local name.
525 :class:`QName` instances are opaque.
Georg Brandl116aa622007-08-15 14:28:22 +0000526
527
528.. _elementtree-treebuilder-objects:
529
530TreeBuilder Objects
531-------------------
532
533
Georg Brandl7f01a132009-09-16 15:58:14 +0000534.. class:: TreeBuilder(element_factory=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000535
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000536 Generic element structure builder. This builder converts a sequence of
537 start, data, and end method calls to a well-formed element structure. You
538 can use this class to build an element structure using a custom XML parser,
539 or a parser for some other XML-like format. The *element_factory* is called
540 to create new :class:`Element` instances when given.
Georg Brandl116aa622007-08-15 14:28:22 +0000541
542
Benjamin Petersone41251e2008-04-25 01:59:09 +0000543 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +0000544
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000545 Flushes the builder buffers, and returns the toplevel document
546 element. Returns an :class:`Element` instance.
Georg Brandl116aa622007-08-15 14:28:22 +0000547
548
Benjamin Petersone41251e2008-04-25 01:59:09 +0000549 .. method:: data(data)
Georg Brandl116aa622007-08-15 14:28:22 +0000550
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000551 Adds text to the current element. *data* is a string. This should be
552 either a bytestring, or a Unicode string.
Georg Brandl116aa622007-08-15 14:28:22 +0000553
554
Benjamin Petersone41251e2008-04-25 01:59:09 +0000555 .. method:: end(tag)
Georg Brandl116aa622007-08-15 14:28:22 +0000556
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000557 Closes the current element. *tag* is the element name. Returns the
558 closed element.
Georg Brandl116aa622007-08-15 14:28:22 +0000559
560
Benjamin Petersone41251e2008-04-25 01:59:09 +0000561 .. method:: start(tag, attrs)
Georg Brandl116aa622007-08-15 14:28:22 +0000562
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000563 Opens a new element. *tag* is the element name. *attrs* is a dictionary
564 containing element attributes. Returns the opened element.
Georg Brandl116aa622007-08-15 14:28:22 +0000565
566
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000567 In addition, a custom :class:`TreeBuilder` object can provide the
568 following method:
Georg Brandl116aa622007-08-15 14:28:22 +0000569
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000570 .. method:: doctype(name, pubid, system)
571
572 Handles a doctype declaration. *name* is the doctype name. *pubid* is
573 the public identifier. *system* is the system identifier. This method
574 does not exist on the default :class:`TreeBuilder` class.
575
Ezio Melottif8754a62010-03-21 07:16:43 +0000576 .. versionadded:: 3.2
Georg Brandl116aa622007-08-15 14:28:22 +0000577
578
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000579.. _elementtree-xmlparser-objects:
Georg Brandl116aa622007-08-15 14:28:22 +0000580
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000581XMLParser Objects
582-----------------
583
584
585.. class:: XMLParser(html=0, target=None, encoding=None)
586
587 :class:`Element` structure builder for XML source data, based on the expat
588 parser. *html* are predefined HTML entities. This flag is not supported by
589 the current implementation. *target* is the target object. If omitted, the
590 builder uses an instance of the standard TreeBuilder class. *encoding* [1]_
591 is optional. If given, the value overrides the encoding specified in the
592 XML file.
Georg Brandl116aa622007-08-15 14:28:22 +0000593
594
Benjamin Petersone41251e2008-04-25 01:59:09 +0000595 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +0000596
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000597 Finishes feeding data to the parser. Returns an element structure.
Georg Brandl116aa622007-08-15 14:28:22 +0000598
599
Benjamin Petersone41251e2008-04-25 01:59:09 +0000600 .. method:: doctype(name, pubid, system)
Georg Brandl116aa622007-08-15 14:28:22 +0000601
Georg Brandl67b21b72010-08-17 15:07:14 +0000602 .. deprecated:: 3.2
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000603 Define the :meth:`TreeBuilder.doctype` method on a custom TreeBuilder
604 target.
Georg Brandl116aa622007-08-15 14:28:22 +0000605
606
Benjamin Petersone41251e2008-04-25 01:59:09 +0000607 .. method:: feed(data)
Georg Brandl116aa622007-08-15 14:28:22 +0000608
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000609 Feeds data to the parser. *data* is encoded data.
Georg Brandl116aa622007-08-15 14:28:22 +0000610
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000611:meth:`XMLParser.feed` calls *target*\'s :meth:`start` method
Christian Heimesd8654cf2007-12-02 15:22:16 +0000612for each opening tag, its :meth:`end` method for each closing tag,
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000613and data is processed by method :meth:`data`. :meth:`XMLParser.close`
Georg Brandl48310cd2009-01-03 21:18:54 +0000614calls *target*\'s method :meth:`close`.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000615:class:`XMLParser` can be used not only for building a tree structure.
Christian Heimesd8654cf2007-12-02 15:22:16 +0000616This is an example of counting the maximum depth of an XML file::
617
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000618 >>> from xml.etree.ElementTree import XMLParser
Christian Heimesd8654cf2007-12-02 15:22:16 +0000619 >>> class MaxDepth: # The target object of the parser
620 ... maxDepth = 0
621 ... depth = 0
622 ... def start(self, tag, attrib): # Called for each opening tag.
Georg Brandl48310cd2009-01-03 21:18:54 +0000623 ... self.depth += 1
Christian Heimesd8654cf2007-12-02 15:22:16 +0000624 ... if self.depth > self.maxDepth:
625 ... self.maxDepth = self.depth
626 ... def end(self, tag): # Called for each closing tag.
627 ... self.depth -= 1
Georg Brandl48310cd2009-01-03 21:18:54 +0000628 ... def data(self, data):
Christian Heimesd8654cf2007-12-02 15:22:16 +0000629 ... pass # We do not need to do anything with data.
630 ... def close(self): # Called when all data has been parsed.
631 ... return self.maxDepth
Georg Brandl48310cd2009-01-03 21:18:54 +0000632 ...
Christian Heimesd8654cf2007-12-02 15:22:16 +0000633 >>> target = MaxDepth()
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000634 >>> parser = XMLParser(target=target)
Christian Heimesd8654cf2007-12-02 15:22:16 +0000635 >>> exampleXml = """
636 ... <a>
637 ... <b>
638 ... </b>
639 ... <b>
640 ... <c>
641 ... <d>
642 ... </d>
643 ... </c>
644 ... </b>
645 ... </a>"""
646 >>> parser.feed(exampleXml)
647 >>> parser.close()
648 4
Christian Heimesb186d002008-03-18 15:15:01 +0000649
650
651.. rubric:: Footnotes
652
653.. [#] The encoding string included in XML output should conform to the
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000654 appropriate standards. For example, "UTF-8" is valid, but "UTF8" is
655 not. See http://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl
Benjamin Petersonad3d5c22009-02-26 03:38:59 +0000656 and http://www.iana.org/assignments/character-sets.