rest25/library/xml.etree.elementtree.rst => rest262/library/xml.etree.elementtree.rst
28
29To create an element instance, use the Element or SubElement factory functions.
30
31The :class:`ElementTree` class can be used to wrap an element structure, and
32convert it from and to XML.
33
34A C implementation of this API is available as :mod:`xml.etree.cElementTree`.
35
n36+See http://effbot.org/zone/element-index.htm for tutorials and links to other
37+docs. Fredrik Lundh's page is also the location of the development version of the
38+xml.etree.ElementTree.
36
37.. _elementtree-functions:
38
39Functions
40---------
41
42
43.. function:: Comment([text])
44
45   Comment element factory.  This factory function creates a special element that
46   will be serialized as an XML comment. The comment string can be either an 8-bit
47   ASCII string or a Unicode string. *text* is a string containing the comment
n48-   string.
49- 
50- 
51-   .. data:: Returns:
52-      :noindex:
53- 
54-      An element instance, representing a comment.
51+   string. Returns an element instance representing a comment.
55
56
57.. function:: dump(elem)
58
59   Writes an element tree or element structure to sys.stdout.  This function should
60   be used for debugging only.
61
62   The exact output format is implementation dependent.  In this version, it's
70   Element factory.  This function returns an object implementing the standard
71   Element interface.  The exact class or type of that object is implementation
72   dependent, but it will always be compatible with the _ElementInterface class in
73   this module.
74
75   The element name, attribute names, and attribute values can be either 8-bit
76   ASCII strings or Unicode strings. *tag* is the element name. *attrib* is an
77   optional dictionary, containing element attributes. *extra* contains additional
n78-   attributes, given as keyword arguments.
n75+   attributes, given as keyword arguments. Returns an element instance.
79- 
80- 
81-   .. data:: Returns:
82-      :noindex:
83- 
84-      An element instance.
85
86
87.. function:: fromstring(text)
88
89   Parses an XML section from a string constant.  Same as XML. *text* is a string
n90-   containing XML data.
n81+   containing XML data. Returns an Element instance.
91- 
92- 
93-   .. data:: Returns:
94-      :noindex:
95- 
96-      An Element instance.
97
98
99.. function:: iselement(element)
100
101   Checks if an object appears to be a valid element object. *element* is an
n102-   element instance.
n87+   element instance. Returns a true value if this is an element object.
103- 
104- 
105-   .. data:: Returns:
106-      :noindex:
107- 
108-      A true value if this is an element object.
109
110
111.. function:: iterparse(source[, events])
112
113   Parses an XML section into an element tree incrementally, and reports what's
114   going on to the user. *source* is a filename or file object containing XML data.
115   *events* is a list of events to report back.  If omitted, only "end" events are
n116-   reported.
n95+   reported. Returns an :term:`iterator` providing ``(event, elem)`` pairs.
117
n97+   .. note::
118
n119-   .. data:: Returns:
n99+      :func:`iterparse` only guarantees that it has seen the ">"
120-      :noindex:
100+      character of a starting tag when it emits a "start" event, so the
101+      attributes are defined, but the contents of the text and tail attributes
102+      are undefined at that point.  The same applies to the element children;
103+      they may or may not be present.
121
n122-      A (event, elem) iterator.
n105+      If you need a fully populated element, look for "end" events instead.
123
124
125.. function:: parse(source[, parser])
126
127   Parses an XML section into an element tree. *source* is a filename or file
128   object containing XML data. *parser* is an optional parser instance.  If not
n129-   given, the standard XMLTreeBuilder parser is used.
n112+   given, the standard XMLTreeBuilder parser is used. Returns an ElementTree
130- 
113+   instance.
131- 
132-   .. data:: Returns:
133-      :noindex:
134- 
135-      An ElementTree instance
136
137
138.. function:: ProcessingInstruction(target[, text])
139
140   PI element factory.  This factory function creates a special element that will
141   be serialized as an XML processing instruction. *target* is a string containing
n142-   the PI target. *text* is a string containing the PI contents, if given.
n120+   the PI target. *text* is a string containing the PI contents, if given. Returns
121+   an element instance, representing a processing instruction.
143
144
n145-   .. data:: Returns:
146-      :noindex:
147- 
148-      An element instance, representing a PI.
149- 
150- 
151-.. function:: SubElement(parent, tag[, attrib[, **extra])
124+.. function:: SubElement(parent, tag[, attrib[,  **extra]])
152
153   Subelement factory.  This function creates an element instance, and appends it
154   to an existing element.
155
156   The element name, attribute names, and attribute values can be either 8-bit
157   ASCII strings or Unicode strings. *parent* is the parent element. *tag* is the
158   subelement name. *attrib* is an optional dictionary, containing element
159   attributes. *extra* contains additional attributes, given as keyword arguments.
n160- 
161- 
162-   .. data:: Returns:
163-      :noindex:
164- 
165-      An element instance.
133+   Returns an element instance.
166
167
168.. function:: tostring(element[, encoding])
169
170   Generates a string representation of an XML element, including all subelements.
171   *element* is an Element instance. *encoding* is the output encoding (default is
n172-   US-ASCII).
173- 
174- 
175-   .. data:: Returns:
176-      :noindex:
177- 
178-      An encoded string containing the XML data.
140+   US-ASCII). Returns an encoded string containing the XML data.
179
180
181.. function:: XML(text)
182
183   Parses an XML section from a string constant.  This function can be used to
184   embed "XML literals" in Python code. *text* is a string containing XML data.
n185- 
186- 
187-   .. data:: Returns:
188-      :noindex:
189- 
190-      An Element instance.
147+   Returns an Element instance.
191
192
193.. function:: XMLID(text)
194
195   Parses an XML section from a string constant, and also returns a dictionary
196   which maps from element id:s to elements. *text* is a string containing XML
n197-   data.
198- 
199- 
200-   .. data:: Returns:
201-      :noindex:
202- 
203-      A tuple containing an Element instance and a dictionary.
154+   data. Returns a tuple containing an Element instance and a dictionary.
155+ 
156+ 
157+.. _elementtree-element-interface:
158+ 
159+The Element Interface
160+---------------------
161+ 
162+Element objects returned by Element or SubElement have the  following methods
163+and attributes.
164+ 
165+ 
166+.. attribute:: Element.tag
167+ 
168+   A string identifying what kind of data this element represents (the element
169+   type, in other words).
170+ 
171+ 
172+.. attribute:: Element.text
173+ 
174+   The *text* attribute can be used to hold additional data associated with the
175+   element. As the name implies this attribute is usually a string but may be any
176+   application-specific object. If the element is created from an XML file the
177+   attribute will contain any text found between the element tags.
178+ 
179+ 
180+.. attribute:: Element.tail
181+ 
182+   The *tail* attribute can be used to hold additional data associated with the
183+   element. This attribute is usually a string but may be any application-specific
184+   object. If the element is created from an XML file the attribute will contain
185+   any text found after the element's end tag and before the next tag.
186+ 
187+ 
188+.. attribute:: Element.attrib
189+ 
190+   A dictionary containing the element's attributes. Note that while the *attrib*
191+   value is always a real mutable Python dictionary, an ElementTree implementation
192+   may choose to use another internal representation, and create the dictionary
193+   only if someone asks for it. To take advantage of such implementations, use the
194+   dictionary methods below whenever possible.
195+ 
196+The following dictionary-like methods work on the element attributes.
197+ 
198+ 
199+.. method:: Element.clear()
200+ 
201+   Resets an element.  This function removes all subelements, clears all
202+   attributes, and sets the text and tail attributes to None.
203+ 
204+ 
205+.. method:: Element.get(key[, default=None])
206+ 
207+   Gets the element attribute named *key*.
208+ 
209+   Returns the attribute value, or *default* if the attribute was not found.
210+ 
211+ 
212+.. method:: Element.items()
213+ 
214+   Returns the element attributes as a sequence of (name, value) pairs. The
215+   attributes are returned in an arbitrary order.
216+ 
217+ 
218+.. method:: Element.keys()
219+ 
220+   Returns the elements attribute names as a list. The names are returned in an
221+   arbitrary order.
222+ 
223+ 
224+.. method:: Element.set(key, value)
225+ 
226+   Set the attribute *key* on the element to *value*.
227+ 
228+The following methods work on the element's children (subelements).
229+ 
230+ 
231+.. method:: Element.append(subelement)
232+ 
233+   Adds the element *subelement* to the end of this elements internal list of
234+   subelements.
235+ 
236+ 
237+.. method:: Element.find(match)
238+ 
239+   Finds the first subelement matching *match*.  *match* may be a tag name or path.
240+   Returns an element instance or ``None``.
241+ 
242+ 
243+.. method:: Element.findall(match)
244+ 
245+   Finds all subelements matching *match*.  *match* may be a tag name or path.
246+   Returns an iterable yielding all matching elements in document order.
247+ 
248+ 
249+.. method:: Element.findtext(condition[, default=None])
250+ 
251+   Finds text for the first subelement matching *condition*.  *condition* may be a
252+   tag name or path. Returns the text content of the first matching element, or
253+   *default* if no element was found.  Note that if the matching element has no
254+   text content an empty string is returned.
255+ 
256+ 
257+.. method:: Element.getchildren()
258+ 
259+   Returns all subelements.  The elements are returned in document order.
260+ 
261+ 
262+.. method:: Element.getiterator([tag=None])
263+ 
264+   Creates a tree iterator with the current element as the root.   The iterator
265+   iterates over this element and all elements below it  that match the given tag.
266+   If tag is ``None`` or ``'*'`` then all elements are iterated over. Returns an
267+   iterable that provides element objects in document (depth first) order.
268+ 
269+ 
270+.. method:: Element.insert(index, element)
271+ 
272+   Inserts a subelement at the given position in this element.
273+ 
274+ 
275+.. method:: Element.makeelement(tag, attrib)
276+ 
277+   Creates a new element object of the same type as this element. Do not call this
278+   method, use the SubElement factory function instead.
279+ 
280+ 
281+.. method:: Element.remove(subelement)
282+ 
283+   Removes *subelement* from the element.   Unlike the findXYZ methods this method
284+   compares elements based on  the instance identity, not on tag value or contents.
285+ 
286+Element objects also support the following sequence type methods for working
287+with subelements: :meth:`__delitem__`, :meth:`__getitem__`, :meth:`__setitem__`,
288+:meth:`__len__`.
289+ 
290+Caution: Because Element objects do not define a :meth:`__nonzero__` method,
291+elements with no subelements will test as ``False``. ::
292+ 
293+   element = root.find('foo')
294+ 
295+   if not element: # careful!
296+       print "element not found, or element has no subelements"
297+ 
298+   if element is None:
299+       print "element not found"
204
205
206.. _elementtree-elementtree-objects:
207
208ElementTree Objects
209-------------------
210
211
213
214   ElementTree wrapper class.  This class represents an entire element hierarchy,
215   and adds some extra support for serialization to and from standard XML.
216
217   *element* is the root element. The tree is initialized with the contents of the
218   XML *file* if given.
219
220
n221-.. method:: ElementTree._setroot(element)
n317+   .. method:: _setroot(element)
222
n223-   Replaces the root element for this tree.  This discards the current contents of
n319+      Replaces the root element for this tree.  This discards the current
224-   the tree, and replaces it with the given element.  Use with care. *element* is
320+      contents of the tree, and replaces it with the given element.  Use with
225-   an element instance.
321+      care. *element* is an element instance.
226
227
n228-.. method:: ElementTree.find(path)
n324+   .. method:: find(path)
229
n230-   Finds the first toplevel element with given tag. Same as getroot().find(path).
n326+      Finds the first toplevel element with given tag. Same as
231-   *path* is the element to look for.
327+      getroot().find(path).  *path* is the element to look for. Returns the
232- 
233- 
234-   .. data:: Returns:
235-      :noindex:
236- 
237-      The first matching element, or None if no element was found.
328+      first matching element, or ``None`` if no element was found.
238
239
n240-.. method:: ElementTree.findall(path)
n331+   .. method:: findall(path)
241
n242-   Finds all toplevel elements with the given tag. Same as getroot().findall(path).
n333+      Finds all toplevel elements with the given tag. Same as
243-   *path* is the element to look for.
334+      getroot().findall(path).  *path* is the element to look for. Returns a
244- 
245- 
246-   .. data:: Returns:
247-      :noindex:
248- 
249-      A list or iterator containing all matching elements, in section order.
335+      list or :term:`iterator` containing all matching elements, in document
336+      order.
250
251
n252-.. method:: ElementTree.findtext(path[, default])
n339+   .. method:: findtext(path[, default])
253
n254-   Finds the element text for the first toplevel element with given tag.  Same as
n341+      Finds the element text for the first toplevel element with given tag.
255-   getroot().findtext(path). *path* is the toplevel element to look for. *default*
342+      Same as getroot().findtext(path). *path* is the toplevel element to look
256-   is the value to return if the element was not found.
343+      for. *default* is the value to return if the element was not
344+      found. Returns the text content of the first matching element, or the
345+      default value no element was found.  Note that if the element has is
346+      found, but has no text content, this method returns an empty string.
257
258
n259-   .. data:: Returns:
260-      :noindex:
261- 
262-      The text content of the first matching element, or the default value no element
263-      was found.  Note that if the element has is found, but has no text content, this
264-      method returns an empty string.
265- 
266- 
267-.. method:: ElementTree.getiterator([tag])
349+   .. method:: getiterator([tag])
268
n269-   Creates a tree iterator for the root element.  The iterator loops over all
n351+      Creates and returns a tree iterator for the root element.  The iterator
270-   elements in this tree, in section order. *tag* is the tag to look for (default
352+      loops over all elements in this tree, in section order. *tag* is the tag
271-   is to return all elements)
353+      to look for (default is to return all elements)
272
273
n274-   .. data:: Returns:
n356+   .. method:: getroot()
275-      :noindex:
276
n277-      An iterator.
278- 
279- 
280-.. method:: ElementTree.getroot()
281- 
282-   Gets the root element for this tree.
358+      Returns the root element for this tree.
283
284
n285-   .. data:: Returns:
286-      :noindex:
287- 
288-      An element instance.
289- 
290- 
291-.. method:: ElementTree.parse(source[, parser])
361+   .. method:: parse(source[, parser])
292
n293-   Loads an external XML section into this element tree. *source* is a file name or
n363+      Loads an external XML section into this element tree. *source* is a file
294-   file object. *parser* is an optional parser instance.  If not given, the
364+      name or file object. *parser* is an optional parser instance.  If not
295-   standard XMLTreeBuilder parser is used.
365+      given, the standard XMLTreeBuilder parser is used. Returns the section
296- 
297- 
298-   .. data:: Returns:
299-      :noindex:
300- 
301-      The section root element.
366+      root element.
302
303
n304-.. method:: ElementTree.write(file[, encoding])
n369+   .. method:: write(file[, encoding])
305
n306-   Writes the element tree to a file, as XML. *file* is a file name, or a file
n371+      Writes the element tree to a file, as XML. *file* is a file name, or a
307-   object opened for writing. *encoding* is the output encoding (default is US-
372+      file object opened for writing. *encoding* [1]_ is the output encoding
308-   ASCII).
373+      (default is US-ASCII).
309
n375+This is the XML file that is going to be manipulated::
376+ 
377+    <html>
378+        <head>
379+            <title>Example page</title>
380+        </head>
381+        <body>
382+            <p>Moved to <a href="http://example.org/">example.org</a>
383+            or <a href="http://example.com/">example.com</a>.</p>
384+        </body>
385+    </html>
386+ 
387+Example of changing the attribute "target" of every link in first paragraph::
388+ 
389+    >>> from xml.etree.ElementTree import ElementTree
390+    >>> tree = ElementTree()
391+    >>> tree.parse("index.xhtml")
392+    <Element html at b7d3f1ec>
393+    >>> p = tree.find("body/p")     # Finds first occurrence of tag p in body
394+    >>> p
395+    <Element p at 8416e0c>
396+    >>> links = p.getiterator("a")  # Returns list of all links
397+    >>> links
398+    [<Element a at b7d4f9ec>, <Element a at b7d4fb0c>]
399+    >>> for i in links:             # Iterates through all found links
400+    ...     i.attrib["target"] = "blank"
401+    >>> tree.write("output.xhtml")
310
311.. _elementtree-qname-objects:
312
313QName Objects
314-------------
315
316
317.. class:: QName(text_or_uri[, tag])
318
319   QName wrapper.  This can be used to wrap a QName attribute value, in order to
320   get proper namespace handling on output. *text_or_uri* is a string containing
321   the QName value, in the form {uri}local, or, if the tag argument is given, the
322   URI part of a QName. If *tag* is given, the first argument is interpreted as an
n323-   URI, and this argument is interpreted as a local name.
n415+   URI, and this argument is interpreted as a local name. :class:`QName` instances
324- 
416+   are opaque.
325- 
326-   .. data:: Returns:
327-      :noindex:
328- 
329-      An opaque object, representing the QName.
330
331
332.. _elementtree-treebuilder-objects:
333
334TreeBuilder Objects
335-------------------
336
337
339
340   Generic element structure builder.  This builder converts a sequence of start,
341   data, and end method calls to a well-formed element structure. You can use this
342   class to build an element structure using a custom XML parser, or a parser for
343   some other XML-like format. The *element_factory* is called to create new
344   Element instances when given.
345
346
n347-.. method:: TreeBuilder.close()
n434+   .. method:: close()
348
n349-   Flushes the parser buffers, and returns the toplevel documen element.
n436+      Flushes the parser buffers, and returns the toplevel document
437+      element. Returns an Element instance.
350
351
n352-   .. data:: Returns:
n440+   .. method:: data(data)
353-      :noindex:
354
n355-      An Element instance.
356- 
357- 
358-.. method:: TreeBuilder.data(data)
359- 
360-   Adds text to the current element. *data* is a string.  This should be either an
442+      Adds text to the current element. *data* is a string.  This should be
361-   8-bit string containing ASCII text, or a Unicode string.
443+      either an 8-bit string containing ASCII text, or a Unicode string.
362
363
n364-.. method:: TreeBuilder.end(tag)
n446+   .. method:: end(tag)
365
n366-   Closes the current element. *tag* is the element name.
n448+      Closes the current element. *tag* is the element name. Returns the closed
449+      element.
367
368
n369-   .. data:: Returns:
370-      :noindex:
371- 
372-      The closed element.
373- 
374- 
375-.. method:: TreeBuilder.start(tag, attrs)
452+   .. method:: start(tag, attrs)
376
n377-   Opens a new element. *tag* is the element name. *attrs* is a dictionary
n454+      Opens a new element. *tag* is the element name. *attrs* is a dictionary
378-   containing element attributes.
455+      containing element attributes. Returns the opened element.
379- 
380- 
381-   .. data:: Returns:
382-      :noindex:
383- 
384-      The opened element.
385
386
387.. _elementtree-xmltreebuilder-objects:
388
389XMLTreeBuilder Objects
390----------------------
391
392
393.. class:: XMLTreeBuilder([html,] [target])
394
395   Element structure builder for XML source data, based on the expat parser. *html*
396   are predefined HTML entities.  This flag is not supported by the current
397   implementation. *target* is the target object.  If omitted, the builder uses an
398   instance of the standard TreeBuilder class.
399
400
n401-.. method:: XMLTreeBuilder.close()
n472+   .. method:: close()
402
n403-   Finishes feeding data to the parser.
n474+      Finishes feeding data to the parser. Returns an element structure.
404
405
n406-   .. data:: Returns:
407-      :noindex:
408- 
409-      An element structure.
410- 
411- 
412-.. method:: XMLTreeBuilder.doctype(name, pubid, system)
477+   .. method:: doctype(name, pubid, system)
413
n414-   Handles a doctype declaration. *name* is the doctype name. *pubid* is the public
n479+      Handles a doctype declaration. *name* is the doctype name. *pubid* is the
415-   identifier. *system* is the system identifier.
480+      public identifier. *system* is the system identifier.
416
417
n418-.. method:: XMLTreeBuilder.feed(data)
n483+   .. method:: feed(data)
419
n420-   Feeds data to the parser.
n485+      Feeds data to the parser. *data* is encoded data.
421
n422-   *data* is encoded data.
n487+:meth:`XMLTreeBuilder.feed` calls *target*\'s :meth:`start` method
488+for each opening tag, its :meth:`end` method for each closing tag,
489+and data is processed by method :meth:`data`. :meth:`XMLTreeBuilder.close`
490+calls *target*\'s method :meth:`close`.
491+:class:`XMLTreeBuilder` can be used not only for building a tree structure.
492+This is an example of counting the maximum depth of an XML file::
423
t494+    >>> from xml.etree.ElementTree import XMLTreeBuilder
495+    >>> class MaxDepth:                     # The target object of the parser
496+    ...     maxDepth = 0
497+    ...     depth = 0
498+    ...     def start(self, tag, attrib):   # Called for each opening tag.
499+    ...         self.depth += 1
500+    ...         if self.depth > self.maxDepth:
501+    ...             self.maxDepth = self.depth
502+    ...     def end(self, tag):             # Called for each closing tag.
503+    ...         self.depth -= 1
504+    ...     def data(self, data):
505+    ...         pass            # We do not need to do anything with data.
506+    ...     def close(self):    # Called when all data has been parsed.
507+    ...         return self.maxDepth
508+    ...
509+    >>> target = MaxDepth()
510+    >>> parser = XMLTreeBuilder(target=target)
511+    >>> exampleXml = """
512+    ... <a>
513+    ...   <b>
514+    ...   </b>
515+    ...   <b>
516+    ...     <c>
517+    ...       <d>
518+    ...       </d>
519+    ...     </c>
520+    ...   </b>
521+    ... </a>"""
522+    >>> parser.feed(exampleXml)
523+    >>> parser.close()
524+    4
525+ 
526+ 
527+.. rubric:: Footnotes
528+ 
529+.. [#] The encoding string included in XML output should conform to the
530+   appropriate standards. For example, "UTF-8" is valid, but "UTF8" is
531+   not. See http://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl
532+   and http://www.iana.org/assignments/character-sets.
533+ 
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op