blob: d9e1b59cd3d1fc3593031dfe4a76ce80352e0cf3 [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
8
Florent Xiclunaf15351d2010-03-13 23:24:31 +00009The :class:`Element` type is a flexible container object, designed to store
10hierarchical data structures in memory. The type can be described as a cross
11between a list and a dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +000012
13Each element has a number of properties associated with it:
14
15* a tag which is a string identifying what kind of data this element represents
16 (the element type, in other words).
17
18* a number of attributes, stored in a Python dictionary.
19
20* a text string.
21
22* an optional tail string.
23
24* a number of child elements, stored in a Python sequence
25
Florent Xiclunaf15351d2010-03-13 23:24:31 +000026To create an element instance, use the :class:`Element` constructor or the
27:func:`SubElement` factory function.
Georg Brandl116aa622007-08-15 14:28:22 +000028
29The :class:`ElementTree` class can be used to wrap an element structure, and
30convert it from and to XML.
31
32A C implementation of this API is available as :mod:`xml.etree.cElementTree`.
33
Christian Heimesd8654cf2007-12-02 15:22:16 +000034See http://effbot.org/zone/element-index.htm for tutorials and links to other
Florent Xiclunaf15351d2010-03-13 23:24:31 +000035docs. Fredrik Lundh's page is also the location of the development version of
36the xml.etree.ElementTree.
37
38.. versionchanged:: 2.7
39 The ElementTree API is updated to 1.3. For more information, see
40 `Introducing ElementTree 1.3
41 <http://effbot.org/zone/elementtree-13-intro.htm>`_.
42
Georg Brandl116aa622007-08-15 14:28:22 +000043
44.. _elementtree-functions:
45
46Functions
47---------
48
49
Georg Brandl7f01a132009-09-16 15:58:14 +000050.. function:: Comment(text=None)
Georg Brandl116aa622007-08-15 14:28:22 +000051
Georg Brandlf6945182008-02-01 11:56:49 +000052 Comment element factory. This factory function creates a special element
Florent Xiclunaf15351d2010-03-13 23:24:31 +000053 that will be serialized as an XML comment by the standard serializer. The
54 comment string can be either a bytestring or a Unicode string. *text* is a
55 string containing the comment string. Returns an element instance
Georg Brandlf6945182008-02-01 11:56:49 +000056 representing a comment.
Georg Brandl116aa622007-08-15 14:28:22 +000057
58
59.. function:: dump(elem)
60
Florent Xiclunaf15351d2010-03-13 23:24:31 +000061 Writes an element tree or element structure to sys.stdout. This function
62 should be used for debugging only.
Georg Brandl116aa622007-08-15 14:28:22 +000063
64 The exact output format is implementation dependent. In this version, it's
65 written as an ordinary XML file.
66
67 *elem* is an element tree or an individual element.
68
69
Georg Brandl116aa622007-08-15 14:28:22 +000070.. function:: fromstring(text)
71
Florent Xiclunaf15351d2010-03-13 23:24:31 +000072 Parses an XML section from a string constant. Same as XML. *text* is a
73 string containing XML data. Returns an :class:`Element` instance.
74
75
76.. function:: fromstringlist(sequence, parser=None)
77
78 Parses an XML document from a sequence of string fragments. *sequence* is a
79 list or other sequence containing XML data fragments. *parser* is an
80 optional parser instance. If not given, the standard :class:`XMLParser`
81 parser is used. Returns an :class:`Element` instance.
82
83 .. versionadded:: 2.7
Georg Brandl116aa622007-08-15 14:28:22 +000084
85
86.. function:: iselement(element)
87
Florent Xiclunaf15351d2010-03-13 23:24:31 +000088 Checks if an object appears to be a valid element object. *element* is an
89 element instance. Returns a true value if this is an element object.
Georg Brandl116aa622007-08-15 14:28:22 +000090
91
Florent Xiclunaf15351d2010-03-13 23:24:31 +000092.. function:: iterparse(source, events=None, parser=None)
Georg Brandl116aa622007-08-15 14:28:22 +000093
94 Parses an XML section into an element tree incrementally, and reports what's
Florent Xiclunaf15351d2010-03-13 23:24:31 +000095 going on to the user. *source* is a filename or file object containing XML
96 data. *events* is a list of events to report back. If omitted, only "end"
97 events are reported. *parser* is an optional parser instance. If not
98 given, the standard :class:`XMLParser` parser is used. Returns an
99 :term:`iterator` providing ``(event, elem)`` pairs.
Georg Brandl116aa622007-08-15 14:28:22 +0000100
Benjamin Peterson75edad02009-01-01 15:05:06 +0000101 .. note::
102
103 :func:`iterparse` only guarantees that it has seen the ">"
104 character of a starting tag when it emits a "start" event, so the
105 attributes are defined, but the contents of the text and tail attributes
106 are undefined at that point. The same applies to the element children;
107 they may or may not be present.
108
109 If you need a fully populated element, look for "end" events instead.
110
Georg Brandl116aa622007-08-15 14:28:22 +0000111
Georg Brandl7f01a132009-09-16 15:58:14 +0000112.. function:: parse(source, parser=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000113
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000114 Parses an XML section into an element tree. *source* is a filename or file
115 object containing XML data. *parser* is an optional parser instance. If
116 not given, the standard :class:`XMLParser` parser is used. Returns an
117 :class:`ElementTree` instance.
Georg Brandl116aa622007-08-15 14:28:22 +0000118
119
Georg Brandl7f01a132009-09-16 15:58:14 +0000120.. function:: ProcessingInstruction(target, text=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000121
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000122 PI element factory. This factory function creates a special element that
123 will be serialized as an XML processing instruction. *target* is a string
124 containing the PI target. *text* is a string containing the PI contents, if
125 given. Returns an element instance, representing a processing instruction.
126
127
128.. function:: register_namespace(prefix, uri)
129
130 Registers a namespace prefix. The registry is global, and any existing
131 mapping for either the given prefix or the namespace URI will be removed.
132 *prefix* is a namespace prefix. *uri* is a namespace uri. Tags and
133 attributes in this namespace will be serialized with the given prefix, if at
134 all possible.
135
136 .. versionadded:: 2.7
Georg Brandl116aa622007-08-15 14:28:22 +0000137
138
Georg Brandl7f01a132009-09-16 15:58:14 +0000139.. function:: SubElement(parent, tag, attrib={}, **extra)
Georg Brandl116aa622007-08-15 14:28:22 +0000140
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000141 Subelement factory. This function creates an element instance, and appends
142 it to an existing element.
Georg Brandl116aa622007-08-15 14:28:22 +0000143
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000144 The element name, attribute names, and attribute values can be either
145 bytestrings or Unicode strings. *parent* is the parent element. *tag* is
146 the subelement name. *attrib* is an optional dictionary, containing element
147 attributes. *extra* contains additional attributes, given as keyword
148 arguments. Returns an element instance.
Georg Brandl116aa622007-08-15 14:28:22 +0000149
150
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000151.. function:: tostring(element, encoding=None, method=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000152
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000153 Generates a string representation of an XML element, including all
154 subelements. *element* is an :class:`Element` instance. *encoding* is the
155 output encoding (default is None). *method* is either ``"xml"``,
156 ``"html"`` or ``"text"`` (default is ``"xml"``). Returns an (optionally)
157 encoded string containing the XML data.
Georg Brandl116aa622007-08-15 14:28:22 +0000158
159
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000160.. function:: tostringlist(element, encoding=None, method=None)
161
162 Generates a string representation of an XML element, including all
163 subelements. *element* is an :class:`Element` instance. *encoding* is the
164 output encoding (default is None). *method* is either ``"xml"``,
165 ``"html"`` or ``"text"`` (default is ``"xml"``). Returns a sequence object
166 containing the XML data.
167
168 .. versionadded:: 2.7
169
170
171.. function:: XML(text, parser=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000172
173 Parses an XML section from a string constant. This function can be used to
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000174 embed "XML literals" in Python code. *text* is a string containing XML
175 data. *parser* is an optional parser instance. If not given, the standard
176 :class:`XMLParser` parser is used. Returns an :class:`Element` instance.
Georg Brandl116aa622007-08-15 14:28:22 +0000177
178
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000179.. function:: XMLID(text, parser=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000180
181 Parses an XML section from a string constant, and also returns a dictionary
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000182 which maps from element id:s to elements. *text* is a string containing XML
183 data. *parser* is an optional parser instance. If not given, the standard
184 :class:`XMLParser` parser is used. Returns a tuple containing an
185 :class:`Element` instance and a dictionary.
Georg Brandl116aa622007-08-15 14:28:22 +0000186
187
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000188.. _elementtree-element-objects:
Georg Brandl116aa622007-08-15 14:28:22 +0000189
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000190Element Objects
191---------------
Georg Brandl116aa622007-08-15 14:28:22 +0000192
Georg Brandl116aa622007-08-15 14:28:22 +0000193
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000194.. class:: Element(tag, attrib={}, **extra)
Georg Brandl116aa622007-08-15 14:28:22 +0000195
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000196 Element class. This class defines the Element interface, and provides a
197 reference implementation of this interface.
Georg Brandl116aa622007-08-15 14:28:22 +0000198
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000199 The element name, attribute names, and attribute values can be either
200 bytestrings or Unicode strings. *tag* is the element name. *attrib* is
201 an optional dictionary, containing element attributes. *extra* contains
202 additional attributes, given as keyword arguments.
Georg Brandl116aa622007-08-15 14:28:22 +0000203
204
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000205 .. attribute:: tag
Georg Brandl116aa622007-08-15 14:28:22 +0000206
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000207 A string identifying what kind of data this element represents (the
208 element type, in other words).
Georg Brandl116aa622007-08-15 14:28:22 +0000209
210
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000211 .. attribute:: text
Georg Brandl116aa622007-08-15 14:28:22 +0000212
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000213 The *text* attribute can be used to hold additional data associated with
214 the element. As the name implies this attribute is usually a string but
215 may be any application-specific object. If the element is created from
216 an XML file the attribute will contain any text found between the element
217 tags.
Georg Brandl116aa622007-08-15 14:28:22 +0000218
219
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000220 .. attribute:: tail
Georg Brandl116aa622007-08-15 14:28:22 +0000221
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000222 The *tail* attribute can be used to hold additional data associated with
223 the element. This attribute is usually a string but may be any
224 application-specific object. If the element is created from an XML file
225 the attribute will contain any text found after the element's end tag and
226 before the next tag.
Georg Brandl116aa622007-08-15 14:28:22 +0000227
Georg Brandl116aa622007-08-15 14:28:22 +0000228
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000229 .. attribute:: attrib
Georg Brandl116aa622007-08-15 14:28:22 +0000230
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000231 A dictionary containing the element's attributes. Note that while the
232 *attrib* value is always a real mutable Python dictionary, an ElementTree
233 implementation may choose to use another internal representation, and
234 create the dictionary only if someone asks for it. To take advantage of
235 such implementations, use the dictionary methods below whenever possible.
Georg Brandl116aa622007-08-15 14:28:22 +0000236
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000237 The following dictionary-like methods work on the element attributes.
Georg Brandl116aa622007-08-15 14:28:22 +0000238
239
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000240 .. method:: clear()
Georg Brandl116aa622007-08-15 14:28:22 +0000241
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000242 Resets an element. This function removes all subelements, clears all
243 attributes, and sets the text and tail attributes to None.
Georg Brandl116aa622007-08-15 14:28:22 +0000244
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000245
246 .. method:: get(key, default=None)
247
248 Gets the element attribute named *key*.
249
250 Returns the attribute value, or *default* if the attribute was not found.
251
252
253 .. method:: items()
254
255 Returns the element attributes as a sequence of (name, value) pairs. The
256 attributes are returned in an arbitrary order.
257
258
259 .. method:: keys()
260
261 Returns the elements attribute names as a list. The names are returned
262 in an arbitrary order.
263
264
265 .. method:: set(key, value)
266
267 Set the attribute *key* on the element to *value*.
268
269 The following methods work on the element's children (subelements).
270
271
272 .. method:: append(subelement)
273
274 Adds the element *subelement* to the end of this elements internal list
275 of subelements.
276
277
278 .. method:: extend(subelements)
Georg Brandl116aa622007-08-15 14:28:22 +0000279
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000280 Appends *subelements* from a sequence object with zero or more elements.
281 Raises :exc:`AssertionError` if a subelement is not a valid object.
Georg Brandl116aa622007-08-15 14:28:22 +0000282
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000283 .. versionadded:: 2.7
Georg Brandl116aa622007-08-15 14:28:22 +0000284
Georg Brandl116aa622007-08-15 14:28:22 +0000285
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000286 .. method:: find(match)
Georg Brandl116aa622007-08-15 14:28:22 +0000287
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000288 Finds the first subelement matching *match*. *match* may be a tag name
289 or path. Returns an element instance or ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000290
Georg Brandl116aa622007-08-15 14:28:22 +0000291
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000292 .. method:: findall(match)
Georg Brandl116aa622007-08-15 14:28:22 +0000293
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000294 Finds all matching subelements, by tag name or path. Returns a list
295 containing all matching elements in document order.
Georg Brandl116aa622007-08-15 14:28:22 +0000296
Georg Brandl116aa622007-08-15 14:28:22 +0000297
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000298 .. method:: findtext(match, default=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000299
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000300 Finds text for the first subelement matching *match*. *match* may be
301 a tag name or path. Returns the text content of the first matching
302 element, or *default* if no element was found. Note that if the matching
303 element has no text content an empty string is returned.
Georg Brandl116aa622007-08-15 14:28:22 +0000304
Georg Brandl116aa622007-08-15 14:28:22 +0000305
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000306 .. method:: getchildren()
Georg Brandl116aa622007-08-15 14:28:22 +0000307
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000308 .. deprecated:: 2.7
309 Use ``list(elem)`` or iteration.
Georg Brandl116aa622007-08-15 14:28:22 +0000310
Georg Brandl116aa622007-08-15 14:28:22 +0000311
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000312 .. method:: getiterator(tag=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000313
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000314 .. deprecated:: 2.7
315 Use method :meth:`Element.iter` instead.
Georg Brandl116aa622007-08-15 14:28:22 +0000316
Georg Brandl116aa622007-08-15 14:28:22 +0000317
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000318 .. method:: insert(index, element)
Georg Brandl116aa622007-08-15 14:28:22 +0000319
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000320 Inserts a subelement at the given position in this element.
Georg Brandl116aa622007-08-15 14:28:22 +0000321
Georg Brandl116aa622007-08-15 14:28:22 +0000322
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000323 .. method:: iter(tag=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000324
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000325 Creates a tree :term:`iterator` with the current element as the root.
326 The iterator iterates over this element and all elements below it, in
327 document (depth first) order. If *tag* is not ``None`` or ``'*'``, only
328 elements whose tag equals *tag* are returned from the iterator. If the
329 tree structure is modified during iteration, the result is undefined.
Georg Brandl116aa622007-08-15 14:28:22 +0000330
Georg Brandl116aa622007-08-15 14:28:22 +0000331
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000332 .. method:: iterfind(match)
Georg Brandl116aa622007-08-15 14:28:22 +0000333
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000334 Finds all matching subelements, by tag name or path. Returns an iterable
335 yielding all matching elements in document order.
Georg Brandl116aa622007-08-15 14:28:22 +0000336
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000337 .. versionadded:: 2.7
Georg Brandl116aa622007-08-15 14:28:22 +0000338
Georg Brandl116aa622007-08-15 14:28:22 +0000339
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000340 .. method:: itertext()
Georg Brandl116aa622007-08-15 14:28:22 +0000341
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000342 Creates a text iterator. The iterator loops over this element and all
343 subelements, in document order, and returns all inner text.
Georg Brandl116aa622007-08-15 14:28:22 +0000344
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000345 .. versionadded:: 2.7
Georg Brandl116aa622007-08-15 14:28:22 +0000346
347
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000348 .. method:: makeelement(tag, attrib)
Georg Brandl116aa622007-08-15 14:28:22 +0000349
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000350 Creates a new element object of the same type as this element. Do not
351 call this method, use the :func:`SubElement` factory function instead.
Georg Brandl116aa622007-08-15 14:28:22 +0000352
353
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000354 .. method:: remove(subelement)
Georg Brandl116aa622007-08-15 14:28:22 +0000355
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000356 Removes *subelement* from the element. Unlike the find\* methods this
357 method compares elements based on the instance identity, not on tag value
358 or contents.
Georg Brandl116aa622007-08-15 14:28:22 +0000359
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000360 :class:`Element` objects also support the following sequence type methods
361 for working with subelements: :meth:`__delitem__`, :meth:`__getitem__`,
362 :meth:`__setitem__`, :meth:`__len__`.
Georg Brandl116aa622007-08-15 14:28:22 +0000363
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000364 Caution: Elements with no subelements will test as ``False``. This behavior
365 will change in future versions. Use specific ``len(elem)`` or ``elem is
366 None`` test instead. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000367
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000368 element = root.find('foo')
Georg Brandl116aa622007-08-15 14:28:22 +0000369
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000370 if not element: # careful!
371 print("element not found, or element has no subelements")
Georg Brandl116aa622007-08-15 14:28:22 +0000372
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000373 if element is None:
374 print("element not found")
Georg Brandl116aa622007-08-15 14:28:22 +0000375
376
377.. _elementtree-elementtree-objects:
378
379ElementTree Objects
380-------------------
381
382
Georg Brandl7f01a132009-09-16 15:58:14 +0000383.. class:: ElementTree(element=None, file=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000384
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000385 ElementTree wrapper class. This class represents an entire element
386 hierarchy, and adds some extra support for serialization to and from
387 standard XML.
Georg Brandl116aa622007-08-15 14:28:22 +0000388
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000389 *element* is the root element. The tree is initialized with the contents
390 of the XML *file* if given.
Georg Brandl116aa622007-08-15 14:28:22 +0000391
392
Benjamin Petersone41251e2008-04-25 01:59:09 +0000393 .. method:: _setroot(element)
Georg Brandl116aa622007-08-15 14:28:22 +0000394
Benjamin Petersone41251e2008-04-25 01:59:09 +0000395 Replaces the root element for this tree. This discards the current
396 contents of the tree, and replaces it with the given element. Use with
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000397 care. *element* is an element instance.
Georg Brandl116aa622007-08-15 14:28:22 +0000398
399
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000400 .. method:: find(match)
Georg Brandl116aa622007-08-15 14:28:22 +0000401
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000402 Finds the first toplevel element matching *match*. *match* may be a tag
403 name or path. Same as getroot().find(match). Returns the first matching
404 element, or ``None`` if no element was found.
Georg Brandl116aa622007-08-15 14:28:22 +0000405
406
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000407 .. method:: findall(match)
Georg Brandl116aa622007-08-15 14:28:22 +0000408
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000409 Finds all matching subelements, by tag name or path. Same as
410 getroot().findall(match). *match* may be a tag name or path. Returns a
411 list containing all matching elements, in document order.
Georg Brandl116aa622007-08-15 14:28:22 +0000412
413
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000414 .. method:: findtext(match, default=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000415
Benjamin Petersone41251e2008-04-25 01:59:09 +0000416 Finds the element text for the first toplevel element with given tag.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000417 Same as getroot().findtext(match). *match* may be a tag name or path.
418 *default* is the value to return if the element was not found. Returns
419 the text content of the first matching element, or the default value no
420 element was found. Note that if the element is found, but has no text
421 content, this method returns an empty string.
Georg Brandl116aa622007-08-15 14:28:22 +0000422
423
Georg Brandl7f01a132009-09-16 15:58:14 +0000424 .. method:: getiterator(tag=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000425
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000426 .. deprecated:: 2.7
427 Use method :meth:`ElementTree.iter` instead.
Georg Brandl116aa622007-08-15 14:28:22 +0000428
429
Benjamin Petersone41251e2008-04-25 01:59:09 +0000430 .. method:: getroot()
Benjamin Petersone41251e2008-04-25 01:59:09 +0000431 Returns the root element for this tree.
Georg Brandl116aa622007-08-15 14:28:22 +0000432
433
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000434 .. method:: iter(tag=None)
435
436 Creates and returns a tree iterator for the root element. The iterator
437 loops over all elements in this tree, in section order. *tag* is the tag
438 to look for (default is to return all elements)
439
440
441 .. method:: iterfind(match)
442
443 Finds all matching subelements, by tag name or path. Same as
444 getroot().iterfind(match). Returns an iterable yielding all matching
445 elements in document order.
446
447 .. versionadded:: 2.7
448
449
Georg Brandl7f01a132009-09-16 15:58:14 +0000450 .. method:: parse(source, parser=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000451
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000452 Loads an external XML section into this element tree. *source* is a file
453 name or file object. *parser* is an optional parser instance. If not
454 given, the standard XMLParser parser is used. Returns the section
Benjamin Petersone41251e2008-04-25 01:59:09 +0000455 root element.
Georg Brandl116aa622007-08-15 14:28:22 +0000456
457
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000458 .. method:: write(file, encoding=None, xml_declaration=None, method=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000459
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000460 Writes the element tree to a file, as XML. *file* is a file name, or a
461 file object opened for writing. *encoding* [1]_ is the output encoding
462 (default is None). *xml_declaration* controls if an XML declaration
463 should be added to the file. Use False for never, True for always, None
464 for only if not US-ASCII or UTF-8 (default is None). *method* is either
465 ``"xml"``, ``"html"`` or ``"text"`` (default is ``"xml"``). Returns an
466 (optionally) encoded string.
Georg Brandl116aa622007-08-15 14:28:22 +0000467
Christian Heimesd8654cf2007-12-02 15:22:16 +0000468This is the XML file that is going to be manipulated::
469
470 <html>
471 <head>
472 <title>Example page</title>
473 </head>
474 <body>
Georg Brandl48310cd2009-01-03 21:18:54 +0000475 <p>Moved to <a href="http://example.org/">example.org</a>
Christian Heimesd8654cf2007-12-02 15:22:16 +0000476 or <a href="http://example.com/">example.com</a>.</p>
477 </body>
478 </html>
479
480Example of changing the attribute "target" of every link in first paragraph::
481
482 >>> from xml.etree.ElementTree import ElementTree
483 >>> tree = ElementTree()
484 >>> tree.parse("index.xhtml")
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000485 <Element 'html' at 0xb77e6fac>
Christian Heimesd8654cf2007-12-02 15:22:16 +0000486 >>> p = tree.find("body/p") # Finds first occurrence of tag p in body
487 >>> p
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000488 <Element 'p' at 0xb77ec26c>
489 >>> links = list(p.iter("a")) # Returns list of all links
Christian Heimesd8654cf2007-12-02 15:22:16 +0000490 >>> links
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000491 [<Element 'a' at 0xb77ec2ac>, <Element 'a' at 0xb77ec1cc>]
Christian Heimesd8654cf2007-12-02 15:22:16 +0000492 >>> for i in links: # Iterates through all found links
493 ... i.attrib["target"] = "blank"
494 >>> tree.write("output.xhtml")
Georg Brandl116aa622007-08-15 14:28:22 +0000495
496.. _elementtree-qname-objects:
497
498QName Objects
499-------------
500
501
Georg Brandl7f01a132009-09-16 15:58:14 +0000502.. class:: QName(text_or_uri, tag=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000503
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000504 QName wrapper. This can be used to wrap a QName attribute value, in order
505 to get proper namespace handling on output. *text_or_uri* is a string
506 containing the QName value, in the form {uri}local, or, if the tag argument
507 is given, the URI part of a QName. If *tag* is given, the first argument is
508 interpreted as an URI, and this argument is interpreted as a local name.
509 :class:`QName` instances are opaque.
Georg Brandl116aa622007-08-15 14:28:22 +0000510
511
512.. _elementtree-treebuilder-objects:
513
514TreeBuilder Objects
515-------------------
516
517
Georg Brandl7f01a132009-09-16 15:58:14 +0000518.. class:: TreeBuilder(element_factory=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000519
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000520 Generic element structure builder. This builder converts a sequence of
521 start, data, and end method calls to a well-formed element structure. You
522 can use this class to build an element structure using a custom XML parser,
523 or a parser for some other XML-like format. The *element_factory* is called
524 to create new :class:`Element` instances when given.
Georg Brandl116aa622007-08-15 14:28:22 +0000525
526
Benjamin Petersone41251e2008-04-25 01:59:09 +0000527 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +0000528
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000529 Flushes the builder buffers, and returns the toplevel document
530 element. Returns an :class:`Element` instance.
Georg Brandl116aa622007-08-15 14:28:22 +0000531
532
Benjamin Petersone41251e2008-04-25 01:59:09 +0000533 .. method:: data(data)
Georg Brandl116aa622007-08-15 14:28:22 +0000534
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000535 Adds text to the current element. *data* is a string. This should be
536 either a bytestring, or a Unicode string.
Georg Brandl116aa622007-08-15 14:28:22 +0000537
538
Benjamin Petersone41251e2008-04-25 01:59:09 +0000539 .. method:: end(tag)
Georg Brandl116aa622007-08-15 14:28:22 +0000540
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000541 Closes the current element. *tag* is the element name. Returns the
542 closed element.
Georg Brandl116aa622007-08-15 14:28:22 +0000543
544
Benjamin Petersone41251e2008-04-25 01:59:09 +0000545 .. method:: start(tag, attrs)
Georg Brandl116aa622007-08-15 14:28:22 +0000546
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000547 Opens a new element. *tag* is the element name. *attrs* is a dictionary
548 containing element attributes. Returns the opened element.
Georg Brandl116aa622007-08-15 14:28:22 +0000549
550
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000551 In addition, a custom :class:`TreeBuilder` object can provide the
552 following method:
Georg Brandl116aa622007-08-15 14:28:22 +0000553
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000554 .. method:: doctype(name, pubid, system)
555
556 Handles a doctype declaration. *name* is the doctype name. *pubid* is
557 the public identifier. *system* is the system identifier. This method
558 does not exist on the default :class:`TreeBuilder` class.
559
560 .. versionadded:: 2.7
Georg Brandl116aa622007-08-15 14:28:22 +0000561
562
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000563.. _elementtree-xmlparser-objects:
Georg Brandl116aa622007-08-15 14:28:22 +0000564
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000565XMLParser Objects
566-----------------
567
568
569.. class:: XMLParser(html=0, target=None, encoding=None)
570
571 :class:`Element` structure builder for XML source data, based on the expat
572 parser. *html* are predefined HTML entities. This flag is not supported by
573 the current implementation. *target* is the target object. If omitted, the
574 builder uses an instance of the standard TreeBuilder class. *encoding* [1]_
575 is optional. If given, the value overrides the encoding specified in the
576 XML file.
Georg Brandl116aa622007-08-15 14:28:22 +0000577
578
Benjamin Petersone41251e2008-04-25 01:59:09 +0000579 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +0000580
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000581 Finishes feeding data to the parser. Returns an element structure.
Georg Brandl116aa622007-08-15 14:28:22 +0000582
583
Benjamin Petersone41251e2008-04-25 01:59:09 +0000584 .. method:: doctype(name, pubid, system)
Georg Brandl116aa622007-08-15 14:28:22 +0000585
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000586 .. deprecated:: 2.7
587 Define the :meth:`TreeBuilder.doctype` method on a custom TreeBuilder
588 target.
Georg Brandl116aa622007-08-15 14:28:22 +0000589
590
Benjamin Petersone41251e2008-04-25 01:59:09 +0000591 .. method:: feed(data)
Georg Brandl116aa622007-08-15 14:28:22 +0000592
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000593 Feeds data to the parser. *data* is encoded data.
Georg Brandl116aa622007-08-15 14:28:22 +0000594
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000595:meth:`XMLParser.feed` calls *target*\'s :meth:`start` method
Christian Heimesd8654cf2007-12-02 15:22:16 +0000596for each opening tag, its :meth:`end` method for each closing tag,
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000597and data is processed by method :meth:`data`. :meth:`XMLParser.close`
Georg Brandl48310cd2009-01-03 21:18:54 +0000598calls *target*\'s method :meth:`close`.
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000599:class:`XMLParser` can be used not only for building a tree structure.
Christian Heimesd8654cf2007-12-02 15:22:16 +0000600This is an example of counting the maximum depth of an XML file::
601
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000602 >>> from xml.etree.ElementTree import XMLParser
Christian Heimesd8654cf2007-12-02 15:22:16 +0000603 >>> class MaxDepth: # The target object of the parser
604 ... maxDepth = 0
605 ... depth = 0
606 ... def start(self, tag, attrib): # Called for each opening tag.
Georg Brandl48310cd2009-01-03 21:18:54 +0000607 ... self.depth += 1
Christian Heimesd8654cf2007-12-02 15:22:16 +0000608 ... if self.depth > self.maxDepth:
609 ... self.maxDepth = self.depth
610 ... def end(self, tag): # Called for each closing tag.
611 ... self.depth -= 1
Georg Brandl48310cd2009-01-03 21:18:54 +0000612 ... def data(self, data):
Christian Heimesd8654cf2007-12-02 15:22:16 +0000613 ... pass # We do not need to do anything with data.
614 ... def close(self): # Called when all data has been parsed.
615 ... return self.maxDepth
Georg Brandl48310cd2009-01-03 21:18:54 +0000616 ...
Christian Heimesd8654cf2007-12-02 15:22:16 +0000617 >>> target = MaxDepth()
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000618 >>> parser = XMLParser(target=target)
Christian Heimesd8654cf2007-12-02 15:22:16 +0000619 >>> exampleXml = """
620 ... <a>
621 ... <b>
622 ... </b>
623 ... <b>
624 ... <c>
625 ... <d>
626 ... </d>
627 ... </c>
628 ... </b>
629 ... </a>"""
630 >>> parser.feed(exampleXml)
631 >>> parser.close()
632 4
Christian Heimesb186d002008-03-18 15:15:01 +0000633
634
635.. rubric:: Footnotes
636
637.. [#] The encoding string included in XML output should conform to the
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000638 appropriate standards. For example, "UTF-8" is valid, but "UTF8" is
639 not. See http://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl
Benjamin Petersonad3d5c22009-02-26 03:38:59 +0000640 and http://www.iana.org/assignments/character-sets.