blob: ed0755d1e102bd12d1a3dacdc84a12e2a9ed371c [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001
2:mod:`xml.etree.ElementTree` --- The ElementTree XML API
3========================================================
4
5.. module:: xml.etree.ElementTree
6 :synopsis: Implementation of the ElementTree API.
7.. moduleauthor:: Fredrik Lundh <fredrik@pythonware.com>
8
9
10.. versionadded:: 2.5
11
Florent Xicluna583302c2010-03-13 17:56:19 +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 Brandl8ec7f652007-08-15 14:28:01 +000015
16Each element has a number of properties associated with it:
17
18* a tag which is a string identifying what kind of data this element represents
19 (the element type, in other words).
20
21* a number of attributes, stored in a Python dictionary.
22
23* a text string.
24
25* an optional tail string.
26
27* a number of child elements, stored in a Python sequence
28
Florent Xicluna3e8c1892010-03-11 14:36:19 +000029To create an element instance, use the :class:`Element` constructor or the
30:func:`SubElement` factory function.
Georg Brandl8ec7f652007-08-15 14:28:01 +000031
32The :class:`ElementTree` class can be used to wrap an element structure, and
33convert it from and to XML.
34
35A C implementation of this API is available as :mod:`xml.etree.cElementTree`.
36
Georg Brandl39bd0592007-12-01 22:42:46 +000037See http://effbot.org/zone/element-index.htm for tutorials and links to other
Florent Xicluna583302c2010-03-13 17:56:19 +000038docs. Fredrik Lundh's page is also the location of the development version of
39the xml.etree.ElementTree.
40
41.. versionchanged:: 2.7
42 The ElementTree API is updated to 1.3. For more information, see
43 `Introducing ElementTree 1.3
44 <http://effbot.org/zone/elementtree-13-intro.htm>`_.
45
Georg Brandl8ec7f652007-08-15 14:28:01 +000046
47.. _elementtree-functions:
48
49Functions
50---------
51
52
53.. function:: Comment([text])
54
Florent Xicluna583302c2010-03-13 17:56:19 +000055 Comment element factory. This factory function creates a special element
56 that will be serialized as an XML comment by the standard serializer. The
57 comment string can be either a bytestring or a Unicode string. *text* is a
58 string containing the comment string. Returns an element instance
59 representing a comment.
Georg Brandl8ec7f652007-08-15 14:28:01 +000060
61
62.. function:: dump(elem)
63
Florent Xicluna583302c2010-03-13 17:56:19 +000064 Writes an element tree or element structure to sys.stdout. This function
65 should be used for debugging only.
Georg Brandl8ec7f652007-08-15 14:28:01 +000066
67 The exact output format is implementation dependent. In this version, it's
68 written as an ordinary XML file.
69
70 *elem* is an element tree or an individual element.
71
72
Georg Brandl8ec7f652007-08-15 14:28:01 +000073.. function:: fromstring(text)
74
Florent Xicluna583302c2010-03-13 17:56:19 +000075 Parses an XML section from a string constant. Same as XML. *text* is a
76 string containing XML data. Returns an :class:`Element` instance.
Georg Brandl8ec7f652007-08-15 14:28:01 +000077
78
Florent Xicluna3e8c1892010-03-11 14:36:19 +000079.. function:: fromstringlist(sequence[, parser])
80
Florent Xicluna583302c2010-03-13 17:56:19 +000081 Parses an XML document from a sequence of string fragments. *sequence* is a
82 list or other sequence containing XML data fragments. *parser* is an
83 optional parser instance. If not given, the standard :class:`XMLParser`
84 parser is used. Returns an :class:`Element` instance.
Florent Xicluna3e8c1892010-03-11 14:36:19 +000085
86 .. versionadded:: 2.7
87
88
Georg Brandl8ec7f652007-08-15 14:28:01 +000089.. function:: iselement(element)
90
Florent Xicluna583302c2010-03-13 17:56:19 +000091 Checks if an object appears to be a valid element object. *element* is an
92 element instance. Returns a true value if this is an element object.
Georg Brandl8ec7f652007-08-15 14:28:01 +000093
94
Florent Xicluna3e8c1892010-03-11 14:36:19 +000095.. function:: iterparse(source[, events[, parser]])
Georg Brandl8ec7f652007-08-15 14:28:01 +000096
97 Parses an XML section into an element tree incrementally, and reports what's
Florent Xicluna583302c2010-03-13 17:56:19 +000098 going on to the user. *source* is a filename or file object containing XML
99 data. *events* is a list of events to report back. If omitted, only "end"
100 events are reported. *parser* is an optional parser instance. If not
101 given, the standard :class:`XMLParser` parser is used. Returns an
102 :term:`iterator` providing ``(event, elem)`` pairs.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000103
Georg Brandlfb222632009-01-01 11:46:51 +0000104 .. note::
105
106 :func:`iterparse` only guarantees that it has seen the ">"
107 character of a starting tag when it emits a "start" event, so the
108 attributes are defined, but the contents of the text and tail attributes
109 are undefined at that point. The same applies to the element children;
110 they may or may not be present.
111
112 If you need a fully populated element, look for "end" events instead.
113
Georg Brandl8ec7f652007-08-15 14:28:01 +0000114
115.. function:: parse(source[, parser])
116
Florent Xicluna583302c2010-03-13 17:56:19 +0000117 Parses an XML section into an element tree. *source* is a filename or file
118 object containing XML data. *parser* is an optional parser instance. If
119 not given, the standard :class:`XMLParser` parser is used. Returns an
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000120 :class:`ElementTree` instance.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000121
122
123.. function:: ProcessingInstruction(target[, text])
124
Florent Xicluna583302c2010-03-13 17:56:19 +0000125 PI element factory. This factory function creates a special element that
126 will be serialized as an XML processing instruction. *target* is a string
127 containing the PI target. *text* is a string containing the PI contents, if
128 given. Returns an element instance, representing a processing instruction.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000129
130
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000131.. function:: register_namespace(prefix, uri)
132
Florent Xicluna583302c2010-03-13 17:56:19 +0000133 Registers a namespace prefix. The registry is global, and any existing
134 mapping for either the given prefix or the namespace URI will be removed.
135 *prefix* is a namespace prefix. *uri* is a namespace uri. Tags and
136 attributes in this namespace will be serialized with the given prefix, if at
137 all possible.
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000138
139 .. versionadded:: 2.7
140
141
Georg Brandl8ec7f652007-08-15 14:28:01 +0000142.. function:: SubElement(parent, tag[, attrib[, **extra]])
143
Florent Xicluna583302c2010-03-13 17:56:19 +0000144 Subelement factory. This function creates an element instance, and appends
145 it to an existing element.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000146
Florent Xicluna583302c2010-03-13 17:56:19 +0000147 The element name, attribute names, and attribute values can be either
148 bytestrings or Unicode strings. *parent* is the parent element. *tag* is
149 the subelement name. *attrib* is an optional dictionary, containing element
150 attributes. *extra* contains additional attributes, given as keyword
151 arguments. Returns an element instance.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000152
153
154.. function:: tostring(element[, encoding])
155
Florent Xicluna583302c2010-03-13 17:56:19 +0000156 Generates a string representation of an XML element, including all
157 subelements. *element* is an :class:`Element` instance. *encoding* is the
158 output encoding (default is US-ASCII). Returns an encoded string containing
159 the XML data.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000160
161
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000162.. function:: tostringlist(element[, encoding])
163
Florent Xicluna583302c2010-03-13 17:56:19 +0000164 Generates a string representation of an XML element, including all
165 subelements. *element* is an :class:`Element` instance. *encoding* is the
166 output encoding (default is US-ASCII). Returns a sequence object containing
167 the XML data.
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000168
169 .. versionadded:: 2.7
170
171
172.. function:: XML(text[, parser])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000173
174 Parses an XML section from a string constant. This function can be used to
Florent Xicluna583302c2010-03-13 17:56:19 +0000175 embed "XML literals" in Python code. *text* is a string containing XML
176 data. *parser* is an optional parser instance. If not given, the standard
177 :class:`XMLParser` parser is used. Returns an :class:`Element` instance.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000178
179
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000180.. function:: XMLID(text[, parser])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000181
182 Parses an XML section from a string constant, and also returns a dictionary
Florent Xicluna583302c2010-03-13 17:56:19 +0000183 which maps from element id:s to elements. *text* is a string containing XML
184 data. *parser* is an optional parser instance. If not given, the standard
185 :class:`XMLParser` parser is used. Returns a tuple containing an
186 :class:`Element` instance and a dictionary.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000187
188
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000189.. _elementtree-element-objects:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000190
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000191Element Objects
192---------------
Georg Brandl8ec7f652007-08-15 14:28:01 +0000193
Georg Brandl8ec7f652007-08-15 14:28:01 +0000194
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000195.. class:: Element(tag[, attrib[, **extra]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000196
Florent Xicluna583302c2010-03-13 17:56:19 +0000197 Element class. This class defines the Element interface, and provides a
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000198 reference implementation of this interface.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000199
Florent Xicluna583302c2010-03-13 17:56:19 +0000200 The element name, attribute names, and attribute values can be either
201 bytestrings or Unicode strings. *tag* is the element name. *attrib* is
202 an optional dictionary, containing element attributes. *extra* contains
203 additional attributes, given as keyword arguments.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000204
205
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000206 .. attribute:: tag
Georg Brandl8ec7f652007-08-15 14:28:01 +0000207
Florent Xicluna583302c2010-03-13 17:56:19 +0000208 A string identifying what kind of data this element represents (the
209 element type, in other words).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000210
211
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000212 .. attribute:: text
Georg Brandl8ec7f652007-08-15 14:28:01 +0000213
Florent Xicluna583302c2010-03-13 17:56:19 +0000214 The *text* attribute can be used to hold additional data associated with
215 the element. As the name implies this attribute is usually a string but
216 may be any application-specific object. If the element is created from
217 an XML file the attribute will contain any text found between the element
218 tags.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000219
220
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000221 .. attribute:: tail
Georg Brandl8ec7f652007-08-15 14:28:01 +0000222
Florent Xicluna583302c2010-03-13 17:56:19 +0000223 The *tail* attribute can be used to hold additional data associated with
224 the element. This attribute is usually a string but may be any
225 application-specific object. If the element is created from an XML file
226 the attribute will contain any text found after the element's end tag and
227 before the next tag.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000228
Georg Brandl8ec7f652007-08-15 14:28:01 +0000229
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000230 .. attribute:: attrib
Georg Brandl8ec7f652007-08-15 14:28:01 +0000231
Florent Xicluna583302c2010-03-13 17:56:19 +0000232 A dictionary containing the element's attributes. Note that while the
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000233 *attrib* value is always a real mutable Python dictionary, an ElementTree
Florent Xicluna583302c2010-03-13 17:56:19 +0000234 implementation may choose to use another internal representation, and
235 create the dictionary only if someone asks for it. To take advantage of
236 such implementations, use the dictionary methods below whenever possible.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000237
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000238 The following dictionary-like methods work on the element attributes.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000239
240
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000241 .. method:: clear()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000242
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000243 Resets an element. This function removes all subelements, clears all
244 attributes, and sets the text and tail attributes to None.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000245
Georg Brandl8ec7f652007-08-15 14:28:01 +0000246
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000247 .. method:: get(key[, default])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000248
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000249 Gets the element attribute named *key*.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000250
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000251 Returns the attribute value, or *default* if the attribute was not found.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000252
253
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000254 .. method:: items()
255
Florent Xicluna583302c2010-03-13 17:56:19 +0000256 Returns the element attributes as a sequence of (name, value) pairs. The
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000257 attributes are returned in an arbitrary order.
258
259
260 .. method:: keys()
261
Florent Xicluna583302c2010-03-13 17:56:19 +0000262 Returns the elements attribute names as a list. The names are returned
263 in an arbitrary order.
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000264
265
266 .. method:: set(key, value)
267
268 Set the attribute *key* on the element to *value*.
269
270 The following methods work on the element's children (subelements).
271
272
273 .. method:: append(subelement)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000274
Florent Xicluna583302c2010-03-13 17:56:19 +0000275 Adds the element *subelement* to the end of this elements internal list
276 of subelements.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000277
278
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000279 .. method:: extend(subelements)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000280
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000281 Appends *subelements* from a sequence object with zero or more elements.
282 Raises :exc:`AssertionError` if a subelement is not a valid object.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000283
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000284 .. versionadded:: 2.7
Georg Brandl8ec7f652007-08-15 14:28:01 +0000285
286
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000287 .. method:: find(match)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000288
Florent Xicluna583302c2010-03-13 17:56:19 +0000289 Finds the first subelement matching *match*. *match* may be a tag name
290 or path. Returns an element instance or ``None``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000291
292
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000293 .. method:: findall(match)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000294
Florent Xicluna583302c2010-03-13 17:56:19 +0000295 Finds all matching subelements, by tag name or path. Returns a list
296 containing all matching elements in document order.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000297
298
Florent Xicluna583302c2010-03-13 17:56:19 +0000299 .. method:: findtext(match[, default])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000300
Florent Xicluna583302c2010-03-13 17:56:19 +0000301 Finds text for the first subelement matching *match*. *match* may be
302 a tag name or path. Returns the text content of the first matching
303 element, or *default* if no element was found. Note that if the matching
304 element has no text content an empty string is returned.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000305
306
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000307 .. method:: getchildren()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000308
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000309 .. deprecated:: 2.7
310 Use ``list(elem)`` or iteration.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000311
312
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000313 .. method:: getiterator([tag])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000314
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000315 .. deprecated:: 2.7
316 Use method :meth:`Element.iter` instead.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000317
318
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000319 .. method:: insert(index, element)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000320
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000321 Inserts a subelement at the given position in this element.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000322
323
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000324 .. method:: iter([tag])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000325
Florent Xicluna583302c2010-03-13 17:56:19 +0000326 Creates a tree :term:`iterator` with the current element as the root.
327 The iterator iterates over this element and all elements below it, in
328 document (depth first) order. If *tag* is not ``None`` or ``'*'``, only
329 elements whose tag equals *tag* are returned from the iterator. If the
330 tree structure is modified during iteration, the result is undefined.
331
332
333 .. method:: iterfind(match)
334
335 Finds all matching subelements, by tag name or path. Returns an iterable
336 yielding all matching elements in document order.
337
338 .. versionadded:: 2.7
339
340
341 .. method:: itertext()
342
343 Creates a text iterator. The iterator loops over this element and all
344 subelements, in document order, and returns all inner text.
345
346 .. versionadded:: 2.7
Georg Brandl8ec7f652007-08-15 14:28:01 +0000347
348
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000349 .. method:: makeelement(tag, attrib)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000350
Florent Xicluna583302c2010-03-13 17:56:19 +0000351 Creates a new element object of the same type as this element. Do not
352 call this method, use the :func:`SubElement` factory function instead.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000353
354
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000355 .. method:: remove(subelement)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000356
Florent Xicluna583302c2010-03-13 17:56:19 +0000357 Removes *subelement* from the element. Unlike the find\* methods this
358 method compares elements based on the instance identity, not on tag value
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000359 or contents.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000360
Florent Xicluna583302c2010-03-13 17:56:19 +0000361 :class:`Element` objects also support the following sequence type methods
362 for working with subelements: :meth:`__delitem__`, :meth:`__getitem__`,
363 :meth:`__setitem__`, :meth:`__len__`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000364
Florent Xicluna583302c2010-03-13 17:56:19 +0000365 Caution: Elements with no subelements will test as ``False``. This behavior
366 will change in future versions. Use specific ``len(elem)`` or ``elem is
367 None`` test instead. ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000368
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000369 element = root.find('foo')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000370
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000371 if not element: # careful!
372 print "element not found, or element has no subelements"
Georg Brandl8ec7f652007-08-15 14:28:01 +0000373
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000374 if element is None:
375 print "element not found"
Georg Brandl8ec7f652007-08-15 14:28:01 +0000376
377
378.. _elementtree-elementtree-objects:
379
380ElementTree Objects
381-------------------
382
383
384.. class:: ElementTree([element,] [file])
385
Florent Xicluna583302c2010-03-13 17:56:19 +0000386 ElementTree wrapper class. This class represents an entire element
387 hierarchy, and adds some extra support for serialization to and from
388 standard XML.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000389
Florent Xicluna583302c2010-03-13 17:56:19 +0000390 *element* is the root element. The tree is initialized with the contents
391 of the XML *file* if given.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000392
393
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000394 .. method:: _setroot(element)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000395
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000396 Replaces the root element for this tree. This discards the current
397 contents of the tree, and replaces it with the given element. Use with
Florent Xicluna583302c2010-03-13 17:56:19 +0000398 care. *element* is an element instance.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000399
400
Florent Xicluna583302c2010-03-13 17:56:19 +0000401 .. method:: find(match)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000402
Florent Xicluna583302c2010-03-13 17:56:19 +0000403 Finds the first toplevel element matching *match*. *match* may be a tag
404 name or path. Same as getroot().find(match). Returns the first matching
405 element, or ``None`` if no element was found.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000406
407
Florent Xicluna583302c2010-03-13 17:56:19 +0000408 .. method:: findall(match)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000409
Florent Xicluna583302c2010-03-13 17:56:19 +0000410 Finds all matching subelements, by tag name or path. Same as
411 getroot().findall(match). *match* may be a tag name or path. Returns a
412 list containing all matching elements, in document order.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000413
414
Florent Xicluna583302c2010-03-13 17:56:19 +0000415 .. method:: findtext(match[, default])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000416
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000417 Finds the element text for the first toplevel element with given tag.
Florent Xicluna583302c2010-03-13 17:56:19 +0000418 Same as getroot().findtext(match). *match* may be a tag name or path.
419 *default* is the value to return if the element was not found. Returns
420 the text content of the first matching element, or the default value no
421 element was found. Note that if the element is found, but has no text
422 content, this method returns an empty string.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000423
424
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000425 .. method:: getiterator([tag])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000426
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000427 .. deprecated:: 2.7
428 Use method :meth:`ElementTree.iter` instead.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000429
430
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000431 .. method:: getroot()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000432
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000433 Returns the root element for this tree.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000434
435
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000436 .. method:: iter([tag])
437
438 Creates and returns a tree iterator for the root element. The iterator
Florent Xicluna583302c2010-03-13 17:56:19 +0000439 loops over all elements in this tree, in section order. *tag* is the tag
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000440 to look for (default is to return all elements)
441
442
Florent Xicluna583302c2010-03-13 17:56:19 +0000443 .. method:: iterfind(match)
444
445 Finds all matching subelements, by tag name or path. Same as
446 getroot().iterfind(match). Returns an iterable yielding all matching
447 elements in document order.
448
449 .. versionadded:: 2.7
450
451
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000452 .. method:: parse(source[, parser])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000453
Florent Xicluna583302c2010-03-13 17:56:19 +0000454 Loads an external XML section into this element tree. *source* is a file
455 name or file object. *parser* is an optional parser instance. If not
456 given, the standard XMLParser parser is used. Returns the section
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000457 root element.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000458
459
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000460 .. method:: write(file[, encoding[, xml_declaration]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000461
Florent Xicluna583302c2010-03-13 17:56:19 +0000462 Writes the element tree to a file, as XML. *file* is a file name, or a
463 file object opened for writing. *encoding* [1]_ is the output encoding
464 (default is US-ASCII). *xml_declaration* controls if an XML declaration
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000465 should be added to the file. Use False for never, True for always, None
466 for only if not US-ASCII or UTF-8. None is default.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000467
Georg Brandl39bd0592007-12-01 22:42:46 +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 Brandlc62ef8b2009-01-03 20:55:06 +0000475 <p>Moved to <a href="http://example.org/">example.org</a>
Georg Brandl39bd0592007-12-01 22:42:46 +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 Xicluna583302c2010-03-13 17:56:19 +0000485 <Element 'html' at 0xb77e6fac>
Georg Brandl39bd0592007-12-01 22:42:46 +0000486 >>> p = tree.find("body/p") # Finds first occurrence of tag p in body
487 >>> p
Florent Xicluna583302c2010-03-13 17:56:19 +0000488 <Element 'p' at 0xb77ec26c>
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000489 >>> links = list(p.iter("a")) # Returns list of all links
Georg Brandl39bd0592007-12-01 22:42:46 +0000490 >>> links
Florent Xicluna583302c2010-03-13 17:56:19 +0000491 [<Element 'a' at 0xb77ec2ac>, <Element 'a' at 0xb77ec1cc>]
Georg Brandl39bd0592007-12-01 22:42:46 +0000492 >>> for i in links: # Iterates through all found links
493 ... i.attrib["target"] = "blank"
494 >>> tree.write("output.xhtml")
Georg Brandl8ec7f652007-08-15 14:28:01 +0000495
496.. _elementtree-qname-objects:
497
498QName Objects
499-------------
500
501
502.. class:: QName(text_or_uri[, tag])
503
Florent Xicluna583302c2010-03-13 17:56:19 +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 Brandl8ec7f652007-08-15 14:28:01 +0000510
511
512.. _elementtree-treebuilder-objects:
513
514TreeBuilder Objects
515-------------------
516
517
518.. class:: TreeBuilder([element_factory])
519
Florent Xicluna583302c2010-03-13 17:56:19 +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 Brandl8ec7f652007-08-15 14:28:01 +0000525
526
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000527 .. method:: close()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000528
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000529 Flushes the builder buffers, and returns the toplevel document
Florent Xicluna583302c2010-03-13 17:56:19 +0000530 element. Returns an :class:`Element` instance.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000531
532
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000533 .. method:: data(data)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000534
Florent Xicluna583302c2010-03-13 17:56:19 +0000535 Adds text to the current element. *data* is a string. This should be
536 either a bytestring, or a Unicode string.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000537
538
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000539 .. method:: end(tag)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000540
Florent Xicluna583302c2010-03-13 17:56:19 +0000541 Closes the current element. *tag* is the element name. Returns the
542 closed element.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000543
544
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000545 .. method:: start(tag, attrs)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000546
Florent Xicluna583302c2010-03-13 17:56:19 +0000547 Opens a new element. *tag* is the element name. *attrs* is a dictionary
548 containing element attributes. Returns the opened element.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000549
550
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000551 In addition, a custom :class:`TreeBuilder` object can provide the
552 following method:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000553
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000554 .. method:: doctype(name, pubid, system)
555
Florent Xicluna583302c2010-03-13 17:56:19 +0000556 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.
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000559
560 .. versionadded:: 2.7
Georg Brandl8ec7f652007-08-15 14:28:01 +0000561
562
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000563.. _elementtree-xmlparser-objects:
564
565XMLParser Objects
566-----------------
567
568
569.. class:: XMLParser([html [, target[, encoding]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000570
Florent Xicluna583302c2010-03-13 17:56:19 +0000571 :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 Brandl8ec7f652007-08-15 14:28:01 +0000577
578
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000579 .. method:: close()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000580
Florent Xicluna583302c2010-03-13 17:56:19 +0000581 Finishes feeding data to the parser. Returns an element structure.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000582
583
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000584 .. method:: doctype(name, pubid, system)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000585
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000586 .. deprecated:: 2.7
587 Define the :meth:`TreeBuilder.doctype` method on a custom TreeBuilder
588 target.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000589
590
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000591 .. method:: feed(data)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000592
Florent Xicluna583302c2010-03-13 17:56:19 +0000593 Feeds data to the parser. *data* is encoded data.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000594
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000595:meth:`XMLParser.feed` calls *target*\'s :meth:`start` method
Georg Brandl39bd0592007-12-01 22:42:46 +0000596for each opening tag, its :meth:`end` method for each closing tag,
Florent Xicluna583302c2010-03-13 17:56:19 +0000597and data is processed by method :meth:`data`. :meth:`XMLParser.close`
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000598calls *target*\'s method :meth:`close`.
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000599:class:`XMLParser` can be used not only for building a tree structure.
Georg Brandl39bd0592007-12-01 22:42:46 +0000600This is an example of counting the maximum depth of an XML file::
601
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000602 >>> from xml.etree.ElementTree import XMLParser
Georg Brandl39bd0592007-12-01 22:42:46 +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 Brandlc62ef8b2009-01-03 20:55:06 +0000607 ... self.depth += 1
Georg Brandl39bd0592007-12-01 22:42:46 +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 Brandlc62ef8b2009-01-03 20:55:06 +0000612 ... def data(self, data):
Georg Brandl39bd0592007-12-01 22:42:46 +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 Brandlc62ef8b2009-01-03 20:55:06 +0000616 ...
Georg Brandl39bd0592007-12-01 22:42:46 +0000617 >>> target = MaxDepth()
Florent Xicluna3e8c1892010-03-11 14:36:19 +0000618 >>> parser = XMLParser(target=target)
Georg Brandl39bd0592007-12-01 22:42:46 +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
Mark Summerfield43da35d2008-03-17 08:28:15 +0000633
634
635.. rubric:: Footnotes
636
637.. [#] The encoding string included in XML output should conform to the
Florent Xicluna583302c2010-03-13 17:56:19 +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
Georg Brandl8b8c2df2009-02-20 08:45:47 +0000640 and http://www.iana.org/assignments/character-sets.