blob: 0d3f61cb34d7e18127f9a085b06730e47ce1f8cb [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
Georg Brandl116aa622007-08-15 14:28:22 +00009The Element type is a flexible container object, designed to store hierarchical
10data structures in memory. The type can be described as a cross between a list
11and a dictionary.
12
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
26To create an element instance, use the Element or SubElement factory functions.
27
28The :class:`ElementTree` class can be used to wrap an element structure, and
29convert it from and to XML.
30
31A C implementation of this API is available as :mod:`xml.etree.cElementTree`.
32
Christian Heimesd8654cf2007-12-02 15:22:16 +000033See http://effbot.org/zone/element-index.htm for tutorials and links to other
Georg Brandl48310cd2009-01-03 21:18:54 +000034docs. Fredrik Lundh's page is also the location of the development version of the
Christian Heimesd8654cf2007-12-02 15:22:16 +000035xml.etree.ElementTree.
Georg Brandl116aa622007-08-15 14:28:22 +000036
37.. _elementtree-functions:
38
39Functions
40---------
41
42
Georg Brandl7f01a132009-09-16 15:58:14 +000043.. function:: Comment(text=None)
Georg Brandl116aa622007-08-15 14:28:22 +000044
Georg Brandlf6945182008-02-01 11:56:49 +000045 Comment element factory. This factory function creates a special element
46 that will be serialized as an XML comment. The comment string can be either
47 an ASCII-only :class:`bytes` object or a :class:`str` object. *text* is a
48 string containing the comment string. Returns an element instance
49 representing a comment.
Georg Brandl116aa622007-08-15 14:28:22 +000050
51
52.. function:: dump(elem)
53
54 Writes an element tree or element structure to sys.stdout. This function should
55 be used for debugging only.
56
57 The exact output format is implementation dependent. In this version, it's
58 written as an ordinary XML file.
59
60 *elem* is an element tree or an individual element.
61
62
Georg Brandl7f01a132009-09-16 15:58:14 +000063.. function:: Element(tag, attrib={}, **extra)
Georg Brandl116aa622007-08-15 14:28:22 +000064
65 Element factory. This function returns an object implementing the standard
66 Element interface. The exact class or type of that object is implementation
67 dependent, but it will always be compatible with the _ElementInterface class in
68 this module.
69
Georg Brandlf6945182008-02-01 11:56:49 +000070 The element name, attribute names, and attribute values can be either an
71 ASCII-only :class:`bytes` object or a :class:`str` object. *tag* is the
72 element name. *attrib* is an optional dictionary, containing element
73 attributes. *extra* contains additional attributes, given as keyword
74 arguments. Returns an element instance.
Georg Brandl116aa622007-08-15 14:28:22 +000075
76
77.. function:: fromstring(text)
78
79 Parses an XML section from a string constant. Same as XML. *text* is a string
80 containing XML data. Returns an Element instance.
81
82
83.. function:: iselement(element)
84
85 Checks if an object appears to be a valid element object. *element* is an
86 element instance. Returns a true value if this is an element object.
87
88
Georg Brandl7f01a132009-09-16 15:58:14 +000089.. function:: iterparse(source, events=None)
Georg Brandl116aa622007-08-15 14:28:22 +000090
91 Parses an XML section into an element tree incrementally, and reports what's
92 going on to the user. *source* is a filename or file object containing XML data.
93 *events* is a list of events to report back. If omitted, only "end" events are
Georg Brandl9afde1c2007-11-01 20:32:30 +000094 reported. Returns an :term:`iterator` providing ``(event, elem)`` pairs.
Georg Brandl116aa622007-08-15 14:28:22 +000095
Benjamin Peterson75edad02009-01-01 15:05:06 +000096 .. note::
97
98 :func:`iterparse` only guarantees that it has seen the ">"
99 character of a starting tag when it emits a "start" event, so the
100 attributes are defined, but the contents of the text and tail attributes
101 are undefined at that point. The same applies to the element children;
102 they may or may not be present.
103
104 If you need a fully populated element, look for "end" events instead.
105
Georg Brandl116aa622007-08-15 14:28:22 +0000106
Georg Brandl7f01a132009-09-16 15:58:14 +0000107.. function:: parse(source, parser=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000108
109 Parses an XML section into an element tree. *source* is a filename or file
110 object containing XML data. *parser* is an optional parser instance. If not
111 given, the standard XMLTreeBuilder parser is used. Returns an ElementTree
112 instance.
113
114
Georg Brandl7f01a132009-09-16 15:58:14 +0000115.. function:: ProcessingInstruction(target, text=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000116
117 PI element factory. This factory function creates a special element that will
118 be serialized as an XML processing instruction. *target* is a string containing
119 the PI target. *text* is a string containing the PI contents, if given. Returns
120 an element instance, representing a processing instruction.
121
122
Georg Brandl7f01a132009-09-16 15:58:14 +0000123.. function:: SubElement(parent, tag, attrib={}, **extra)
Georg Brandl116aa622007-08-15 14:28:22 +0000124
125 Subelement factory. This function creates an element instance, and appends it
126 to an existing element.
127
Georg Brandlf6945182008-02-01 11:56:49 +0000128 The element name, attribute names, and attribute values can be an ASCII-only
129 :class:`bytes` object or a :class:`str` object. *parent* is the parent
130 element. *tag* is the subelement name. *attrib* is an optional dictionary,
131 containing element attributes. *extra* contains additional attributes, given
132 as keyword arguments. Returns an element instance.
Georg Brandl116aa622007-08-15 14:28:22 +0000133
134
Georg Brandl7f01a132009-09-16 15:58:14 +0000135.. function:: tostring(element, encoding=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000136
137 Generates a string representation of an XML element, including all subelements.
138 *element* is an Element instance. *encoding* is the output encoding (default is
139 US-ASCII). Returns an encoded string containing the XML data.
140
141
142.. function:: XML(text)
143
144 Parses an XML section from a string constant. This function can be used to
145 embed "XML literals" in Python code. *text* is a string containing XML data.
146 Returns an Element instance.
147
148
149.. function:: XMLID(text)
150
151 Parses an XML section from a string constant, and also returns a dictionary
152 which maps from element id:s to elements. *text* is a string containing XML
153 data. Returns a tuple containing an Element instance and a dictionary.
154
155
156.. _elementtree-element-interface:
157
158The Element Interface
159---------------------
160
161Element objects returned by Element or SubElement have the following methods
162and attributes.
163
164
165.. attribute:: Element.tag
166
167 A string identifying what kind of data this element represents (the element
168 type, in other words).
169
170
171.. attribute:: Element.text
172
173 The *text* attribute can be used to hold additional data associated with the
174 element. As the name implies this attribute is usually a string but may be any
175 application-specific object. If the element is created from an XML file the
176 attribute will contain any text found between the element tags.
177
178
179.. attribute:: Element.tail
180
181 The *tail* attribute can be used to hold additional data associated with the
182 element. This attribute is usually a string but may be any application-specific
183 object. If the element is created from an XML file the attribute will contain
184 any text found after the element's end tag and before the next tag.
185
186
187.. attribute:: Element.attrib
188
189 A dictionary containing the element's attributes. Note that while the *attrib*
190 value is always a real mutable Python dictionary, an ElementTree implementation
191 may choose to use another internal representation, and create the dictionary
192 only if someone asks for it. To take advantage of such implementations, use the
193 dictionary methods below whenever possible.
194
195The following dictionary-like methods work on the element attributes.
196
197
198.. method:: Element.clear()
199
200 Resets an element. This function removes all subelements, clears all
201 attributes, and sets the text and tail attributes to None.
202
203
Georg Brandl7f01a132009-09-16 15:58:14 +0000204.. method:: Element.get(key, default=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000205
206 Gets the element attribute named *key*.
207
208 Returns the attribute value, or *default* if the attribute was not found.
209
210
211.. method:: Element.items()
212
213 Returns the element attributes as a sequence of (name, value) pairs. The
214 attributes are returned in an arbitrary order.
215
216
217.. method:: Element.keys()
218
219 Returns the elements attribute names as a list. The names are returned in an
220 arbitrary order.
221
222
223.. method:: Element.set(key, value)
224
225 Set the attribute *key* on the element to *value*.
226
227The following methods work on the element's children (subelements).
228
229
230.. method:: Element.append(subelement)
231
232 Adds the element *subelement* to the end of this elements internal list of
233 subelements.
234
235
236.. method:: Element.find(match)
237
238 Finds the first subelement matching *match*. *match* may be a tag name or path.
239 Returns an element instance or ``None``.
240
241
242.. method:: Element.findall(match)
243
244 Finds all subelements matching *match*. *match* may be a tag name or path.
245 Returns an iterable yielding all matching elements in document order.
246
247
Georg Brandl7f01a132009-09-16 15:58:14 +0000248.. method:: Element.findtext(condition, default=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000249
250 Finds text for the first subelement matching *condition*. *condition* may be a
251 tag name or path. Returns the text content of the first matching element, or
252 *default* if no element was found. Note that if the matching element has no
253 text content an empty string is returned.
254
255
256.. method:: Element.getchildren()
257
258 Returns all subelements. The elements are returned in document order.
259
260
Georg Brandl7f01a132009-09-16 15:58:14 +0000261.. method:: Element.getiterator(tag=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000262
263 Creates a tree iterator with the current element as the root. The iterator
Alexandre Vassalotti6d3dfc32009-07-29 19:54:39 +0000264 iterates over this element and all elements below it, in document (depth first)
265 order. If *tag* is not ``None`` or ``'*'``, only elements whose tag equals
266 *tag* are returned from the iterator.
Georg Brandl116aa622007-08-15 14:28:22 +0000267
268
269.. method:: Element.insert(index, element)
270
271 Inserts a subelement at the given position in this element.
272
273
274.. method:: Element.makeelement(tag, attrib)
275
276 Creates a new element object of the same type as this element. Do not call this
277 method, use the SubElement factory function instead.
278
279
280.. method:: Element.remove(subelement)
281
282 Removes *subelement* from the element. Unlike the findXYZ methods this method
283 compares elements based on the instance identity, not on tag value or contents.
284
285Element objects also support the following sequence type methods for working
286with subelements: :meth:`__delitem__`, :meth:`__getitem__`, :meth:`__setitem__`,
287:meth:`__len__`.
288
Georg Brandlf6945182008-02-01 11:56:49 +0000289Caution: Because Element objects do not define a :meth:`__bool__` method,
Georg Brandl116aa622007-08-15 14:28:22 +0000290elements with no subelements will test as ``False``. ::
291
292 element = root.find('foo')
293
294 if not element: # careful!
Collin Winterc79461b2007-09-01 23:34:30 +0000295 print("element not found, or element has no subelements")
Georg Brandl116aa622007-08-15 14:28:22 +0000296
297 if element is None:
Collin Winterc79461b2007-09-01 23:34:30 +0000298 print("element not found")
Georg Brandl116aa622007-08-15 14:28:22 +0000299
300
301.. _elementtree-elementtree-objects:
302
303ElementTree Objects
304-------------------
305
306
Georg Brandl7f01a132009-09-16 15:58:14 +0000307.. class:: ElementTree(element=None, file=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000308
309 ElementTree wrapper class. This class represents an entire element hierarchy,
310 and adds some extra support for serialization to and from standard XML.
311
312 *element* is the root element. The tree is initialized with the contents of the
313 XML *file* if given.
314
315
Benjamin Petersone41251e2008-04-25 01:59:09 +0000316 .. method:: _setroot(element)
Georg Brandl116aa622007-08-15 14:28:22 +0000317
Benjamin Petersone41251e2008-04-25 01:59:09 +0000318 Replaces the root element for this tree. This discards the current
319 contents of the tree, and replaces it with the given element. Use with
320 care. *element* is an element instance.
Georg Brandl116aa622007-08-15 14:28:22 +0000321
322
Benjamin Petersone41251e2008-04-25 01:59:09 +0000323 .. method:: find(path)
Georg Brandl116aa622007-08-15 14:28:22 +0000324
Benjamin Petersone41251e2008-04-25 01:59:09 +0000325 Finds the first toplevel element with given tag. Same as
326 getroot().find(path). *path* is the element to look for. Returns the
327 first matching element, or ``None`` if no element was found.
Georg Brandl116aa622007-08-15 14:28:22 +0000328
329
Benjamin Petersone41251e2008-04-25 01:59:09 +0000330 .. method:: findall(path)
Georg Brandl116aa622007-08-15 14:28:22 +0000331
Benjamin Petersone41251e2008-04-25 01:59:09 +0000332 Finds all toplevel elements with the given tag. Same as
333 getroot().findall(path). *path* is the element to look for. Returns a
334 list or :term:`iterator` containing all matching elements, in document
335 order.
Georg Brandl116aa622007-08-15 14:28:22 +0000336
337
Georg Brandl7f01a132009-09-16 15:58:14 +0000338 .. method:: findtext(path, default=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000339
Benjamin Petersone41251e2008-04-25 01:59:09 +0000340 Finds the element text for the first toplevel element with given tag.
341 Same as getroot().findtext(path). *path* is the toplevel element to look
342 for. *default* is the value to return if the element was not
343 found. Returns the text content of the first matching element, or the
344 default value no element was found. Note that if the element has is
345 found, but has no text content, this method returns an empty string.
Georg Brandl116aa622007-08-15 14:28:22 +0000346
347
Georg Brandl7f01a132009-09-16 15:58:14 +0000348 .. method:: getiterator(tag=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000349
Benjamin Petersone41251e2008-04-25 01:59:09 +0000350 Creates and returns a tree iterator for the root element. The iterator
351 loops over all elements in this tree, in section order. *tag* is the tag
352 to look for (default is to return all elements)
Georg Brandl116aa622007-08-15 14:28:22 +0000353
354
Benjamin Petersone41251e2008-04-25 01:59:09 +0000355 .. method:: getroot()
Georg Brandl116aa622007-08-15 14:28:22 +0000356
Benjamin Petersone41251e2008-04-25 01:59:09 +0000357 Returns the root element for this tree.
Georg Brandl116aa622007-08-15 14:28:22 +0000358
359
Georg Brandl7f01a132009-09-16 15:58:14 +0000360 .. method:: parse(source, parser=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000361
Benjamin Petersone41251e2008-04-25 01:59:09 +0000362 Loads an external XML section into this element tree. *source* is a file
363 name or file object. *parser* is an optional parser instance. If not
364 given, the standard XMLTreeBuilder parser is used. Returns the section
365 root element.
Georg Brandl116aa622007-08-15 14:28:22 +0000366
367
Georg Brandl7f01a132009-09-16 15:58:14 +0000368 .. method:: write(file, encoding=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000369
Benjamin Petersone41251e2008-04-25 01:59:09 +0000370 Writes the element tree to a file, as XML. *file* is a file name, or a
371 file object opened for writing. *encoding* [1]_ is the output encoding
372 (default is US-ASCII).
Georg Brandl116aa622007-08-15 14:28:22 +0000373
Christian Heimesd8654cf2007-12-02 15:22:16 +0000374This is the XML file that is going to be manipulated::
375
376 <html>
377 <head>
378 <title>Example page</title>
379 </head>
380 <body>
Georg Brandl48310cd2009-01-03 21:18:54 +0000381 <p>Moved to <a href="http://example.org/">example.org</a>
Christian Heimesd8654cf2007-12-02 15:22:16 +0000382 or <a href="http://example.com/">example.com</a>.</p>
383 </body>
384 </html>
385
386Example of changing the attribute "target" of every link in first paragraph::
387
388 >>> from xml.etree.ElementTree import ElementTree
389 >>> tree = ElementTree()
390 >>> tree.parse("index.xhtml")
391 <Element html at b7d3f1ec>
392 >>> p = tree.find("body/p") # Finds first occurrence of tag p in body
393 >>> p
394 <Element p at 8416e0c>
395 >>> links = p.getiterator("a") # Returns list of all links
396 >>> links
397 [<Element a at b7d4f9ec>, <Element a at b7d4fb0c>]
398 >>> for i in links: # Iterates through all found links
399 ... i.attrib["target"] = "blank"
400 >>> tree.write("output.xhtml")
Georg Brandl116aa622007-08-15 14:28:22 +0000401
402.. _elementtree-qname-objects:
403
404QName Objects
405-------------
406
407
Georg Brandl7f01a132009-09-16 15:58:14 +0000408.. class:: QName(text_or_uri, tag=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000409
410 QName wrapper. This can be used to wrap a QName attribute value, in order to
411 get proper namespace handling on output. *text_or_uri* is a string containing
412 the QName value, in the form {uri}local, or, if the tag argument is given, the
413 URI part of a QName. If *tag* is given, the first argument is interpreted as an
414 URI, and this argument is interpreted as a local name. :class:`QName` instances
415 are opaque.
416
417
418.. _elementtree-treebuilder-objects:
419
420TreeBuilder Objects
421-------------------
422
423
Georg Brandl7f01a132009-09-16 15:58:14 +0000424.. class:: TreeBuilder(element_factory=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000425
426 Generic element structure builder. This builder converts a sequence of start,
427 data, and end method calls to a well-formed element structure. You can use this
428 class to build an element structure using a custom XML parser, or a parser for
429 some other XML-like format. The *element_factory* is called to create new
430 Element instances when given.
431
432
Benjamin Petersone41251e2008-04-25 01:59:09 +0000433 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +0000434
Benjamin Petersone41251e2008-04-25 01:59:09 +0000435 Flushes the parser buffers, and returns the toplevel document
436 element. Returns an Element instance.
Georg Brandl116aa622007-08-15 14:28:22 +0000437
438
Benjamin Petersone41251e2008-04-25 01:59:09 +0000439 .. method:: data(data)
Georg Brandl116aa622007-08-15 14:28:22 +0000440
Benjamin Petersone41251e2008-04-25 01:59:09 +0000441 Adds text to the current element. *data* is a string. This should be
442 either an ASCII-only :class:`bytes` object or a :class:`str` object.
Georg Brandl116aa622007-08-15 14:28:22 +0000443
444
Benjamin Petersone41251e2008-04-25 01:59:09 +0000445 .. method:: end(tag)
Georg Brandl116aa622007-08-15 14:28:22 +0000446
Benjamin Petersone41251e2008-04-25 01:59:09 +0000447 Closes the current element. *tag* is the element name. Returns the closed
448 element.
Georg Brandl116aa622007-08-15 14:28:22 +0000449
450
Benjamin Petersone41251e2008-04-25 01:59:09 +0000451 .. method:: start(tag, attrs)
Georg Brandl116aa622007-08-15 14:28:22 +0000452
Benjamin Petersone41251e2008-04-25 01:59:09 +0000453 Opens a new element. *tag* is the element name. *attrs* is a dictionary
454 containing element attributes. Returns the opened element.
Georg Brandl116aa622007-08-15 14:28:22 +0000455
456
457.. _elementtree-xmltreebuilder-objects:
458
459XMLTreeBuilder Objects
460----------------------
461
462
Georg Brandl7f01a132009-09-16 15:58:14 +0000463.. class:: XMLTreeBuilder(html=0, target=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000464
465 Element structure builder for XML source data, based on the expat parser. *html*
466 are predefined HTML entities. This flag is not supported by the current
467 implementation. *target* is the target object. If omitted, the builder uses an
468 instance of the standard TreeBuilder class.
469
470
Benjamin Petersone41251e2008-04-25 01:59:09 +0000471 .. method:: close()
Georg Brandl116aa622007-08-15 14:28:22 +0000472
Benjamin Petersone41251e2008-04-25 01:59:09 +0000473 Finishes feeding data to the parser. Returns an element structure.
Georg Brandl116aa622007-08-15 14:28:22 +0000474
475
Benjamin Petersone41251e2008-04-25 01:59:09 +0000476 .. method:: doctype(name, pubid, system)
Georg Brandl116aa622007-08-15 14:28:22 +0000477
Benjamin Petersone41251e2008-04-25 01:59:09 +0000478 Handles a doctype declaration. *name* is the doctype name. *pubid* is the
479 public identifier. *system* is the system identifier.
Georg Brandl116aa622007-08-15 14:28:22 +0000480
481
Benjamin Petersone41251e2008-04-25 01:59:09 +0000482 .. method:: feed(data)
Georg Brandl116aa622007-08-15 14:28:22 +0000483
Benjamin Petersone41251e2008-04-25 01:59:09 +0000484 Feeds data to the parser. *data* is encoded data.
Georg Brandl116aa622007-08-15 14:28:22 +0000485
Christian Heimesd8654cf2007-12-02 15:22:16 +0000486:meth:`XMLTreeBuilder.feed` calls *target*\'s :meth:`start` method
487for each opening tag, its :meth:`end` method for each closing tag,
Georg Brandl48310cd2009-01-03 21:18:54 +0000488and data is processed by method :meth:`data`. :meth:`XMLTreeBuilder.close`
489calls *target*\'s method :meth:`close`.
490:class:`XMLTreeBuilder` can be used not only for building a tree structure.
Christian Heimesd8654cf2007-12-02 15:22:16 +0000491This is an example of counting the maximum depth of an XML file::
492
493 >>> from xml.etree.ElementTree import XMLTreeBuilder
494 >>> class MaxDepth: # The target object of the parser
495 ... maxDepth = 0
496 ... depth = 0
497 ... def start(self, tag, attrib): # Called for each opening tag.
Georg Brandl48310cd2009-01-03 21:18:54 +0000498 ... self.depth += 1
Christian Heimesd8654cf2007-12-02 15:22:16 +0000499 ... if self.depth > self.maxDepth:
500 ... self.maxDepth = self.depth
501 ... def end(self, tag): # Called for each closing tag.
502 ... self.depth -= 1
Georg Brandl48310cd2009-01-03 21:18:54 +0000503 ... def data(self, data):
Christian Heimesd8654cf2007-12-02 15:22:16 +0000504 ... pass # We do not need to do anything with data.
505 ... def close(self): # Called when all data has been parsed.
506 ... return self.maxDepth
Georg Brandl48310cd2009-01-03 21:18:54 +0000507 ...
Christian Heimesd8654cf2007-12-02 15:22:16 +0000508 >>> target = MaxDepth()
509 >>> parser = XMLTreeBuilder(target=target)
510 >>> exampleXml = """
511 ... <a>
512 ... <b>
513 ... </b>
514 ... <b>
515 ... <c>
516 ... <d>
517 ... </d>
518 ... </c>
519 ... </b>
520 ... </a>"""
521 >>> parser.feed(exampleXml)
522 >>> parser.close()
523 4
Christian Heimesb186d002008-03-18 15:15:01 +0000524
525
526.. rubric:: Footnotes
527
528.. [#] The encoding string included in XML output should conform to the
529 appropriate standards. For example, "UTF-8" is valid, but "UTF8" is
530 not. See http://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl
Benjamin Petersonad3d5c22009-02-26 03:38:59 +0000531 and http://www.iana.org/assignments/character-sets.
Christian Heimesb186d002008-03-18 15:15:01 +0000532