blob: 172a2a0effd4b289272332c6b4e3101666e945eb [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +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
Georg Brandl116aa622007-08-15 14:28:22 +000010The Element type is a flexible container object, designed to store hierarchical
11data structures in memory. The type can be described as a cross between a list
12and a dictionary.
13
14Each element has a number of properties associated with it:
15
16* a tag which is a string identifying what kind of data this element represents
17 (the element type, in other words).
18
19* a number of attributes, stored in a Python dictionary.
20
21* a text string.
22
23* an optional tail string.
24
25* a number of child elements, stored in a Python sequence
26
27To create an element instance, use the Element or SubElement factory functions.
28
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
35docs. Fredrik Lundh's page is also the location of the development version of the
36xml.etree.ElementTree.
Georg Brandl116aa622007-08-15 14:28:22 +000037
38.. _elementtree-functions:
39
40Functions
41---------
42
43
44.. function:: Comment([text])
45
46 Comment element factory. This factory function creates a special element that
47 will be serialized as an XML comment. The comment string can be either an 8-bit
48 ASCII string or a Unicode string. *text* is a string containing the comment
49 string. Returns an element instance representing a comment.
50
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
63.. function:: Element(tag[, attrib][, **extra])
64
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
70 The element name, attribute names, and attribute values can be either 8-bit
71 ASCII strings or Unicode strings. *tag* is the element name. *attrib* is an
72 optional dictionary, containing element attributes. *extra* contains additional
73 attributes, given as keyword arguments. Returns an element instance.
74
75
76.. function:: fromstring(text)
77
78 Parses an XML section from a string constant. Same as XML. *text* is a string
79 containing XML data. Returns an Element instance.
80
81
82.. function:: iselement(element)
83
84 Checks if an object appears to be a valid element object. *element* is an
85 element instance. Returns a true value if this is an element object.
86
87
88.. function:: iterparse(source[, events])
89
90 Parses an XML section into an element tree incrementally, and reports what's
91 going on to the user. *source* is a filename or file object containing XML data.
92 *events* is a list of events to report back. If omitted, only "end" events are
Georg Brandl9afde1c2007-11-01 20:32:30 +000093 reported. Returns an :term:`iterator` providing ``(event, elem)`` pairs.
Georg Brandl116aa622007-08-15 14:28:22 +000094
95
96.. function:: parse(source[, parser])
97
98 Parses an XML section into an element tree. *source* is a filename or file
99 object containing XML data. *parser* is an optional parser instance. If not
100 given, the standard XMLTreeBuilder parser is used. Returns an ElementTree
101 instance.
102
103
104.. function:: ProcessingInstruction(target[, text])
105
106 PI element factory. This factory function creates a special element that will
107 be serialized as an XML processing instruction. *target* is a string containing
108 the PI target. *text* is a string containing the PI contents, if given. Returns
109 an element instance, representing a processing instruction.
110
111
112.. function:: SubElement(parent, tag[, attrib[, **extra]])
113
114 Subelement factory. This function creates an element instance, and appends it
115 to an existing element.
116
117 The element name, attribute names, and attribute values can be either 8-bit
118 ASCII strings or Unicode strings. *parent* is the parent element. *tag* is the
119 subelement name. *attrib* is an optional dictionary, containing element
120 attributes. *extra* contains additional attributes, given as keyword arguments.
121 Returns an element instance.
122
123
124.. function:: tostring(element[, encoding])
125
126 Generates a string representation of an XML element, including all subelements.
127 *element* is an Element instance. *encoding* is the output encoding (default is
128 US-ASCII). Returns an encoded string containing the XML data.
129
130
131.. function:: XML(text)
132
133 Parses an XML section from a string constant. This function can be used to
134 embed "XML literals" in Python code. *text* is a string containing XML data.
135 Returns an Element instance.
136
137
138.. function:: XMLID(text)
139
140 Parses an XML section from a string constant, and also returns a dictionary
141 which maps from element id:s to elements. *text* is a string containing XML
142 data. Returns a tuple containing an Element instance and a dictionary.
143
144
145.. _elementtree-element-interface:
146
147The Element Interface
148---------------------
149
150Element objects returned by Element or SubElement have the following methods
151and attributes.
152
153
154.. attribute:: Element.tag
155
156 A string identifying what kind of data this element represents (the element
157 type, in other words).
158
159
160.. attribute:: Element.text
161
162 The *text* attribute can be used to hold additional data associated with the
163 element. As the name implies this attribute is usually a string but may be any
164 application-specific object. If the element is created from an XML file the
165 attribute will contain any text found between the element tags.
166
167
168.. attribute:: Element.tail
169
170 The *tail* attribute can be used to hold additional data associated with the
171 element. This attribute is usually a string but may be any application-specific
172 object. If the element is created from an XML file the attribute will contain
173 any text found after the element's end tag and before the next tag.
174
175
176.. attribute:: Element.attrib
177
178 A dictionary containing the element's attributes. Note that while the *attrib*
179 value is always a real mutable Python dictionary, an ElementTree implementation
180 may choose to use another internal representation, and create the dictionary
181 only if someone asks for it. To take advantage of such implementations, use the
182 dictionary methods below whenever possible.
183
184The following dictionary-like methods work on the element attributes.
185
186
187.. method:: Element.clear()
188
189 Resets an element. This function removes all subelements, clears all
190 attributes, and sets the text and tail attributes to None.
191
192
193.. method:: Element.get(key[, default=None])
194
195 Gets the element attribute named *key*.
196
197 Returns the attribute value, or *default* if the attribute was not found.
198
199
200.. method:: Element.items()
201
202 Returns the element attributes as a sequence of (name, value) pairs. The
203 attributes are returned in an arbitrary order.
204
205
206.. method:: Element.keys()
207
208 Returns the elements attribute names as a list. The names are returned in an
209 arbitrary order.
210
211
212.. method:: Element.set(key, value)
213
214 Set the attribute *key* on the element to *value*.
215
216The following methods work on the element's children (subelements).
217
218
219.. method:: Element.append(subelement)
220
221 Adds the element *subelement* to the end of this elements internal list of
222 subelements.
223
224
225.. method:: Element.find(match)
226
227 Finds the first subelement matching *match*. *match* may be a tag name or path.
228 Returns an element instance or ``None``.
229
230
231.. method:: Element.findall(match)
232
233 Finds all subelements matching *match*. *match* may be a tag name or path.
234 Returns an iterable yielding all matching elements in document order.
235
236
237.. method:: Element.findtext(condition[, default=None])
238
239 Finds text for the first subelement matching *condition*. *condition* may be a
240 tag name or path. Returns the text content of the first matching element, or
241 *default* if no element was found. Note that if the matching element has no
242 text content an empty string is returned.
243
244
245.. method:: Element.getchildren()
246
247 Returns all subelements. The elements are returned in document order.
248
249
250.. method:: Element.getiterator([tag=None])
251
252 Creates a tree iterator with the current element as the root. The iterator
253 iterates over this element and all elements below it that match the given tag.
254 If tag is ``None`` or ``'*'`` then all elements are iterated over. Returns an
255 iterable that provides element objects in document (depth first) order.
256
257
258.. method:: Element.insert(index, element)
259
260 Inserts a subelement at the given position in this element.
261
262
263.. method:: Element.makeelement(tag, attrib)
264
265 Creates a new element object of the same type as this element. Do not call this
266 method, use the SubElement factory function instead.
267
268
269.. method:: Element.remove(subelement)
270
271 Removes *subelement* from the element. Unlike the findXYZ methods this method
272 compares elements based on the instance identity, not on tag value or contents.
273
274Element objects also support the following sequence type methods for working
275with subelements: :meth:`__delitem__`, :meth:`__getitem__`, :meth:`__setitem__`,
276:meth:`__len__`.
277
278Caution: Because Element objects do not define a :meth:`__nonzero__` method,
279elements with no subelements will test as ``False``. ::
280
281 element = root.find('foo')
282
283 if not element: # careful!
Collin Winterc79461b2007-09-01 23:34:30 +0000284 print("element not found, or element has no subelements")
Georg Brandl116aa622007-08-15 14:28:22 +0000285
286 if element is None:
Collin Winterc79461b2007-09-01 23:34:30 +0000287 print("element not found")
Georg Brandl116aa622007-08-15 14:28:22 +0000288
289
290.. _elementtree-elementtree-objects:
291
292ElementTree Objects
293-------------------
294
295
296.. class:: ElementTree([element,] [file])
297
298 ElementTree wrapper class. This class represents an entire element hierarchy,
299 and adds some extra support for serialization to and from standard XML.
300
301 *element* is the root element. The tree is initialized with the contents of the
302 XML *file* if given.
303
304
305.. method:: ElementTree._setroot(element)
306
307 Replaces the root element for this tree. This discards the current contents of
308 the tree, and replaces it with the given element. Use with care. *element* is
309 an element instance.
310
311
312.. method:: ElementTree.find(path)
313
314 Finds the first toplevel element with given tag. Same as getroot().find(path).
315 *path* is the element to look for. Returns the first matching element, or
316 ``None`` if no element was found.
317
318
319.. method:: ElementTree.findall(path)
320
321 Finds all toplevel elements with the given tag. Same as getroot().findall(path).
Georg Brandl9afde1c2007-11-01 20:32:30 +0000322 *path* is the element to look for. Returns a list or :term:`iterator` containing all
Georg Brandl116aa622007-08-15 14:28:22 +0000323 matching elements, in document order.
324
325
326.. method:: ElementTree.findtext(path[, default])
327
328 Finds the element text for the first toplevel element with given tag. Same as
329 getroot().findtext(path). *path* is the toplevel element to look for. *default*
330 is the value to return if the element was not found. Returns the text content of
331 the first matching element, or the default value no element was found. Note
332 that if the element has is found, but has no text content, this method returns
333 an empty string.
334
335
336.. method:: ElementTree.getiterator([tag])
337
338 Creates and returns a tree iterator for the root element. The iterator loops
339 over all elements in this tree, in section order. *tag* is the tag to look for
340 (default is to return all elements)
341
342
343.. method:: ElementTree.getroot()
344
345 Returns the root element for this tree.
346
347
348.. method:: ElementTree.parse(source[, parser])
349
350 Loads an external XML section into this element tree. *source* is a file name or
351 file object. *parser* is an optional parser instance. If not given, the
352 standard XMLTreeBuilder parser is used. Returns the section root element.
353
354
355.. method:: ElementTree.write(file[, encoding])
356
357 Writes the element tree to a file, as XML. *file* is a file name, or a file
358 object opened for writing. *encoding* is the output encoding (default is
359 US-ASCII).
360
Christian Heimesd8654cf2007-12-02 15:22:16 +0000361This is the XML file that is going to be manipulated::
362
363 <html>
364 <head>
365 <title>Example page</title>
366 </head>
367 <body>
368 <p>Moved to <a href="http://example.org/">example.org</a>
369 or <a href="http://example.com/">example.com</a>.</p>
370 </body>
371 </html>
372
373Example of changing the attribute "target" of every link in first paragraph::
374
375 >>> from xml.etree.ElementTree import ElementTree
376 >>> tree = ElementTree()
377 >>> tree.parse("index.xhtml")
378 <Element html at b7d3f1ec>
379 >>> p = tree.find("body/p") # Finds first occurrence of tag p in body
380 >>> p
381 <Element p at 8416e0c>
382 >>> links = p.getiterator("a") # Returns list of all links
383 >>> links
384 [<Element a at b7d4f9ec>, <Element a at b7d4fb0c>]
385 >>> for i in links: # Iterates through all found links
386 ... i.attrib["target"] = "blank"
387 >>> tree.write("output.xhtml")
Georg Brandl116aa622007-08-15 14:28:22 +0000388
389.. _elementtree-qname-objects:
390
391QName Objects
392-------------
393
394
395.. class:: QName(text_or_uri[, tag])
396
397 QName wrapper. This can be used to wrap a QName attribute value, in order to
398 get proper namespace handling on output. *text_or_uri* is a string containing
399 the QName value, in the form {uri}local, or, if the tag argument is given, the
400 URI part of a QName. If *tag* is given, the first argument is interpreted as an
401 URI, and this argument is interpreted as a local name. :class:`QName` instances
402 are opaque.
403
404
405.. _elementtree-treebuilder-objects:
406
407TreeBuilder Objects
408-------------------
409
410
411.. class:: TreeBuilder([element_factory])
412
413 Generic element structure builder. This builder converts a sequence of start,
414 data, and end method calls to a well-formed element structure. You can use this
415 class to build an element structure using a custom XML parser, or a parser for
416 some other XML-like format. The *element_factory* is called to create new
417 Element instances when given.
418
419
420.. method:: TreeBuilder.close()
421
422 Flushes the parser buffers, and returns the toplevel documen element. Returns an
423 Element instance.
424
425
426.. method:: TreeBuilder.data(data)
427
428 Adds text to the current element. *data* is a string. This should be either an
429 8-bit string containing ASCII text, or a Unicode string.
430
431
432.. method:: TreeBuilder.end(tag)
433
434 Closes the current element. *tag* is the element name. Returns the closed
435 element.
436
437
438.. method:: TreeBuilder.start(tag, attrs)
439
440 Opens a new element. *tag* is the element name. *attrs* is a dictionary
441 containing element attributes. Returns the opened element.
442
443
444.. _elementtree-xmltreebuilder-objects:
445
446XMLTreeBuilder Objects
447----------------------
448
449
450.. class:: XMLTreeBuilder([html,] [target])
451
452 Element structure builder for XML source data, based on the expat parser. *html*
453 are predefined HTML entities. This flag is not supported by the current
454 implementation. *target* is the target object. If omitted, the builder uses an
455 instance of the standard TreeBuilder class.
456
457
458.. method:: XMLTreeBuilder.close()
459
460 Finishes feeding data to the parser. Returns an element structure.
461
462
463.. method:: XMLTreeBuilder.doctype(name, pubid, system)
464
465 Handles a doctype declaration. *name* is the doctype name. *pubid* is the public
466 identifier. *system* is the system identifier.
467
468
469.. method:: XMLTreeBuilder.feed(data)
470
471 Feeds data to the parser. *data* is encoded data.
472
Christian Heimesd8654cf2007-12-02 15:22:16 +0000473:meth:`XMLTreeBuilder.feed` calls *target*\'s :meth:`start` method
474for each opening tag, its :meth:`end` method for each closing tag,
475and data is processed by method :meth:`data`. :meth:`XMLTreeBuilder.close`
476calls *target*\'s method :meth:`close`.
477:class:`XMLTreeBuilder` can be used not only for building a tree structure.
478This is an example of counting the maximum depth of an XML file::
479
480 >>> from xml.etree.ElementTree import XMLTreeBuilder
481 >>> class MaxDepth: # The target object of the parser
482 ... maxDepth = 0
483 ... depth = 0
484 ... def start(self, tag, attrib): # Called for each opening tag.
485 ... self.depth += 1
486 ... if self.depth > self.maxDepth:
487 ... self.maxDepth = self.depth
488 ... def end(self, tag): # Called for each closing tag.
489 ... self.depth -= 1
490 ... def data(self, data):
491 ... pass # We do not need to do anything with data.
492 ... def close(self): # Called when all data has been parsed.
493 ... return self.maxDepth
494 ...
495 >>> target = MaxDepth()
496 >>> parser = XMLTreeBuilder(target=target)
497 >>> exampleXml = """
498 ... <a>
499 ... <b>
500 ... </b>
501 ... <b>
502 ... <c>
503 ... <d>
504 ... </d>
505 ... </c>
506 ... </b>
507 ... </a>"""
508 >>> parser.feed(exampleXml)
509 >>> parser.close()
510 4