/Doc/library/xml.etree.elementtree.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 533 lines · 328 code · 205 blank · 0 comment · 0 complexity · 3a28c779f7b79bd72cbb6d7ee33f116c MD5 · raw file

  1. :mod:`xml.etree.ElementTree` --- The ElementTree XML API
  2. ========================================================
  3. .. module:: xml.etree.ElementTree
  4. :synopsis: Implementation of the ElementTree API.
  5. .. moduleauthor:: Fredrik Lundh <fredrik@pythonware.com>
  6. .. versionadded:: 2.5
  7. The Element type is a flexible container object, designed to store hierarchical
  8. data structures in memory. The type can be described as a cross between a list
  9. and a dictionary.
  10. Each element has a number of properties associated with it:
  11. * a tag which is a string identifying what kind of data this element represents
  12. (the element type, in other words).
  13. * a number of attributes, stored in a Python dictionary.
  14. * a text string.
  15. * an optional tail string.
  16. * a number of child elements, stored in a Python sequence
  17. To create an element instance, use the Element or SubElement factory functions.
  18. The :class:`ElementTree` class can be used to wrap an element structure, and
  19. convert it from and to XML.
  20. A C implementation of this API is available as :mod:`xml.etree.cElementTree`.
  21. See http://effbot.org/zone/element-index.htm for tutorials and links to other
  22. docs. Fredrik Lundh's page is also the location of the development version of the
  23. xml.etree.ElementTree.
  24. .. _elementtree-functions:
  25. Functions
  26. ---------
  27. .. function:: Comment([text])
  28. Comment element factory. This factory function creates a special element that
  29. will be serialized as an XML comment. The comment string can be either an 8-bit
  30. ASCII string or a Unicode string. *text* is a string containing the comment
  31. string. Returns an element instance representing a comment.
  32. .. function:: dump(elem)
  33. Writes an element tree or element structure to sys.stdout. This function should
  34. be used for debugging only.
  35. The exact output format is implementation dependent. In this version, it's
  36. written as an ordinary XML file.
  37. *elem* is an element tree or an individual element.
  38. .. function:: Element(tag[, attrib][, **extra])
  39. Element factory. This function returns an object implementing the standard
  40. Element interface. The exact class or type of that object is implementation
  41. dependent, but it will always be compatible with the _ElementInterface class in
  42. this module.
  43. The element name, attribute names, and attribute values can be either 8-bit
  44. ASCII strings or Unicode strings. *tag* is the element name. *attrib* is an
  45. optional dictionary, containing element attributes. *extra* contains additional
  46. attributes, given as keyword arguments. Returns an element instance.
  47. .. function:: fromstring(text)
  48. Parses an XML section from a string constant. Same as XML. *text* is a string
  49. containing XML data. Returns an Element instance.
  50. .. function:: iselement(element)
  51. Checks if an object appears to be a valid element object. *element* is an
  52. element instance. Returns a true value if this is an element object.
  53. .. function:: iterparse(source[, events])
  54. Parses an XML section into an element tree incrementally, and reports what's
  55. going on to the user. *source* is a filename or file object containing XML data.
  56. *events* is a list of events to report back. If omitted, only "end" events are
  57. reported. Returns an :term:`iterator` providing ``(event, elem)`` pairs.
  58. .. note::
  59. :func:`iterparse` only guarantees that it has seen the ">"
  60. character of a starting tag when it emits a "start" event, so the
  61. attributes are defined, but the contents of the text and tail attributes
  62. are undefined at that point. The same applies to the element children;
  63. they may or may not be present.
  64. If you need a fully populated element, look for "end" events instead.
  65. .. function:: parse(source[, parser])
  66. Parses an XML section into an element tree. *source* is a filename or file
  67. object containing XML data. *parser* is an optional parser instance. If not
  68. given, the standard XMLTreeBuilder parser is used. Returns an ElementTree
  69. instance.
  70. .. function:: ProcessingInstruction(target[, text])
  71. PI element factory. This factory function creates a special element that will
  72. be serialized as an XML processing instruction. *target* is a string containing
  73. the PI target. *text* is a string containing the PI contents, if given. Returns
  74. an element instance, representing a processing instruction.
  75. .. function:: SubElement(parent, tag[, attrib[, **extra]])
  76. Subelement factory. This function creates an element instance, and appends it
  77. to an existing element.
  78. The element name, attribute names, and attribute values can be either 8-bit
  79. ASCII strings or Unicode strings. *parent* is the parent element. *tag* is the
  80. subelement name. *attrib* is an optional dictionary, containing element
  81. attributes. *extra* contains additional attributes, given as keyword arguments.
  82. Returns an element instance.
  83. .. function:: tostring(element[, encoding])
  84. Generates a string representation of an XML element, including all subelements.
  85. *element* is an Element instance. *encoding* is the output encoding (default is
  86. US-ASCII). Returns an encoded string containing the XML data.
  87. .. function:: XML(text)
  88. Parses an XML section from a string constant. This function can be used to
  89. embed "XML literals" in Python code. *text* is a string containing XML data.
  90. Returns an Element instance.
  91. .. function:: XMLID(text)
  92. Parses an XML section from a string constant, and also returns a dictionary
  93. which maps from element id:s to elements. *text* is a string containing XML
  94. data. Returns a tuple containing an Element instance and a dictionary.
  95. .. _elementtree-element-interface:
  96. The Element Interface
  97. ---------------------
  98. Element objects returned by Element or SubElement have the following methods
  99. and attributes.
  100. .. attribute:: Element.tag
  101. A string identifying what kind of data this element represents (the element
  102. type, in other words).
  103. .. attribute:: Element.text
  104. The *text* attribute can be used to hold additional data associated with the
  105. element. As the name implies this attribute is usually a string but may be any
  106. application-specific object. If the element is created from an XML file the
  107. attribute will contain any text found between the element tags.
  108. .. attribute:: Element.tail
  109. The *tail* attribute can be used to hold additional data associated with the
  110. element. This attribute is usually a string but may be any application-specific
  111. object. If the element is created from an XML file the attribute will contain
  112. any text found after the element's end tag and before the next tag.
  113. .. attribute:: Element.attrib
  114. A dictionary containing the element's attributes. Note that while the *attrib*
  115. value is always a real mutable Python dictionary, an ElementTree implementation
  116. may choose to use another internal representation, and create the dictionary
  117. only if someone asks for it. To take advantage of such implementations, use the
  118. dictionary methods below whenever possible.
  119. The following dictionary-like methods work on the element attributes.
  120. .. method:: Element.clear()
  121. Resets an element. This function removes all subelements, clears all
  122. attributes, and sets the text and tail attributes to None.
  123. .. method:: Element.get(key[, default=None])
  124. Gets the element attribute named *key*.
  125. Returns the attribute value, or *default* if the attribute was not found.
  126. .. method:: Element.items()
  127. Returns the element attributes as a sequence of (name, value) pairs. The
  128. attributes are returned in an arbitrary order.
  129. .. method:: Element.keys()
  130. Returns the elements attribute names as a list. The names are returned in an
  131. arbitrary order.
  132. .. method:: Element.set(key, value)
  133. Set the attribute *key* on the element to *value*.
  134. The following methods work on the element's children (subelements).
  135. .. method:: Element.append(subelement)
  136. Adds the element *subelement* to the end of this elements internal list of
  137. subelements.
  138. .. method:: Element.find(match)
  139. Finds the first subelement matching *match*. *match* may be a tag name or path.
  140. Returns an element instance or ``None``.
  141. .. method:: Element.findall(match)
  142. Finds all subelements matching *match*. *match* may be a tag name or path.
  143. Returns an iterable yielding all matching elements in document order.
  144. .. method:: Element.findtext(condition[, default=None])
  145. Finds text for the first subelement matching *condition*. *condition* may be a
  146. tag name or path. Returns the text content of the first matching element, or
  147. *default* if no element was found. Note that if the matching element has no
  148. text content an empty string is returned.
  149. .. method:: Element.getchildren()
  150. Returns all subelements. The elements are returned in document order.
  151. .. method:: Element.getiterator([tag=None])
  152. Creates a tree iterator with the current element as the root. The iterator
  153. iterates over this element and all elements below it that match the given tag.
  154. If tag is ``None`` or ``'*'`` then all elements are iterated over. Returns an
  155. iterable that provides element objects in document (depth first) order.
  156. .. method:: Element.insert(index, element)
  157. Inserts a subelement at the given position in this element.
  158. .. method:: Element.makeelement(tag, attrib)
  159. Creates a new element object of the same type as this element. Do not call this
  160. method, use the SubElement factory function instead.
  161. .. method:: Element.remove(subelement)
  162. Removes *subelement* from the element. Unlike the findXYZ methods this method
  163. compares elements based on the instance identity, not on tag value or contents.
  164. Element objects also support the following sequence type methods for working
  165. with subelements: :meth:`__delitem__`, :meth:`__getitem__`, :meth:`__setitem__`,
  166. :meth:`__len__`.
  167. Caution: Because Element objects do not define a :meth:`__nonzero__` method,
  168. elements with no subelements will test as ``False``. ::
  169. element = root.find('foo')
  170. if not element: # careful!
  171. print "element not found, or element has no subelements"
  172. if element is None:
  173. print "element not found"
  174. .. _elementtree-elementtree-objects:
  175. ElementTree Objects
  176. -------------------
  177. .. class:: ElementTree([element,] [file])
  178. ElementTree wrapper class. This class represents an entire element hierarchy,
  179. and adds some extra support for serialization to and from standard XML.
  180. *element* is the root element. The tree is initialized with the contents of the
  181. XML *file* if given.
  182. .. method:: _setroot(element)
  183. Replaces the root element for this tree. This discards the current
  184. contents of the tree, and replaces it with the given element. Use with
  185. care. *element* is an element instance.
  186. .. method:: find(path)
  187. Finds the first toplevel element with given tag. Same as
  188. getroot().find(path). *path* is the element to look for. Returns the
  189. first matching element, or ``None`` if no element was found.
  190. .. method:: findall(path)
  191. Finds all toplevel elements with the given tag. Same as
  192. getroot().findall(path). *path* is the element to look for. Returns a
  193. list or :term:`iterator` containing all matching elements, in document
  194. order.
  195. .. method:: findtext(path[, default])
  196. Finds the element text for the first toplevel element with given tag.
  197. Same as getroot().findtext(path). *path* is the toplevel element to look
  198. for. *default* is the value to return if the element was not
  199. found. Returns the text content of the first matching element, or the
  200. default value no element was found. Note that if the element has is
  201. found, but has no text content, this method returns an empty string.
  202. .. method:: getiterator([tag])
  203. Creates and returns a tree iterator for the root element. The iterator
  204. loops over all elements in this tree, in section order. *tag* is the tag
  205. to look for (default is to return all elements)
  206. .. method:: getroot()
  207. Returns the root element for this tree.
  208. .. method:: parse(source[, parser])
  209. Loads an external XML section into this element tree. *source* is a file
  210. name or file object. *parser* is an optional parser instance. If not
  211. given, the standard XMLTreeBuilder parser is used. Returns the section
  212. root element.
  213. .. method:: write(file[, encoding])
  214. Writes the element tree to a file, as XML. *file* is a file name, or a
  215. file object opened for writing. *encoding* [1]_ is the output encoding
  216. (default is US-ASCII).
  217. This is the XML file that is going to be manipulated::
  218. <html>
  219. <head>
  220. <title>Example page</title>
  221. </head>
  222. <body>
  223. <p>Moved to <a href="http://example.org/">example.org</a>
  224. or <a href="http://example.com/">example.com</a>.</p>
  225. </body>
  226. </html>
  227. Example of changing the attribute "target" of every link in first paragraph::
  228. >>> from xml.etree.ElementTree import ElementTree
  229. >>> tree = ElementTree()
  230. >>> tree.parse("index.xhtml")
  231. <Element html at b7d3f1ec>
  232. >>> p = tree.find("body/p") # Finds first occurrence of tag p in body
  233. >>> p
  234. <Element p at 8416e0c>
  235. >>> links = p.getiterator("a") # Returns list of all links
  236. >>> links
  237. [<Element a at b7d4f9ec>, <Element a at b7d4fb0c>]
  238. >>> for i in links: # Iterates through all found links
  239. ... i.attrib["target"] = "blank"
  240. >>> tree.write("output.xhtml")
  241. .. _elementtree-qname-objects:
  242. QName Objects
  243. -------------
  244. .. class:: QName(text_or_uri[, tag])
  245. QName wrapper. This can be used to wrap a QName attribute value, in order to
  246. get proper namespace handling on output. *text_or_uri* is a string containing
  247. the QName value, in the form {uri}local, or, if the tag argument is given, the
  248. URI part of a QName. If *tag* is given, the first argument is interpreted as an
  249. URI, and this argument is interpreted as a local name. :class:`QName` instances
  250. are opaque.
  251. .. _elementtree-treebuilder-objects:
  252. TreeBuilder Objects
  253. -------------------
  254. .. class:: TreeBuilder([element_factory])
  255. Generic element structure builder. This builder converts a sequence of start,
  256. data, and end method calls to a well-formed element structure. You can use this
  257. class to build an element structure using a custom XML parser, or a parser for
  258. some other XML-like format. The *element_factory* is called to create new
  259. Element instances when given.
  260. .. method:: close()
  261. Flushes the parser buffers, and returns the toplevel document
  262. element. Returns an Element instance.
  263. .. method:: data(data)
  264. Adds text to the current element. *data* is a string. This should be
  265. either an 8-bit string containing ASCII text, or a Unicode string.
  266. .. method:: end(tag)
  267. Closes the current element. *tag* is the element name. Returns the closed
  268. element.
  269. .. method:: start(tag, attrs)
  270. Opens a new element. *tag* is the element name. *attrs* is a dictionary
  271. containing element attributes. Returns the opened element.
  272. .. _elementtree-xmltreebuilder-objects:
  273. XMLTreeBuilder Objects
  274. ----------------------
  275. .. class:: XMLTreeBuilder([html,] [target])
  276. Element structure builder for XML source data, based on the expat parser. *html*
  277. are predefined HTML entities. This flag is not supported by the current
  278. implementation. *target* is the target object. If omitted, the builder uses an
  279. instance of the standard TreeBuilder class.
  280. .. method:: close()
  281. Finishes feeding data to the parser. Returns an element structure.
  282. .. method:: doctype(name, pubid, system)
  283. Handles a doctype declaration. *name* is the doctype name. *pubid* is the
  284. public identifier. *system* is the system identifier.
  285. .. method:: feed(data)
  286. Feeds data to the parser. *data* is encoded data.
  287. :meth:`XMLTreeBuilder.feed` calls *target*\'s :meth:`start` method
  288. for each opening tag, its :meth:`end` method for each closing tag,
  289. and data is processed by method :meth:`data`. :meth:`XMLTreeBuilder.close`
  290. calls *target*\'s method :meth:`close`.
  291. :class:`XMLTreeBuilder` can be used not only for building a tree structure.
  292. This is an example of counting the maximum depth of an XML file::
  293. >>> from xml.etree.ElementTree import XMLTreeBuilder
  294. >>> class MaxDepth: # The target object of the parser
  295. ... maxDepth = 0
  296. ... depth = 0
  297. ... def start(self, tag, attrib): # Called for each opening tag.
  298. ... self.depth += 1
  299. ... if self.depth > self.maxDepth:
  300. ... self.maxDepth = self.depth
  301. ... def end(self, tag): # Called for each closing tag.
  302. ... self.depth -= 1
  303. ... def data(self, data):
  304. ... pass # We do not need to do anything with data.
  305. ... def close(self): # Called when all data has been parsed.
  306. ... return self.maxDepth
  307. ...
  308. >>> target = MaxDepth()
  309. >>> parser = XMLTreeBuilder(target=target)
  310. >>> exampleXml = """
  311. ... <a>
  312. ... <b>
  313. ... </b>
  314. ... <b>
  315. ... <c>
  316. ... <d>
  317. ... </d>
  318. ... </c>
  319. ... </b>
  320. ... </a>"""
  321. >>> parser.feed(exampleXml)
  322. >>> parser.close()
  323. 4
  324. .. rubric:: Footnotes
  325. .. [#] The encoding string included in XML output should conform to the
  326. appropriate standards. For example, "UTF-8" is valid, but "UTF8" is
  327. not. See http://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl
  328. and http://www.iana.org/assignments/character-sets.