Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1 | |
| 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 Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 10 | The Element type is a flexible container object, designed to store hierarchical |
| 11 | data structures in memory. The type can be described as a cross between a list |
| 12 | and a dictionary. |
| 13 | |
| 14 | Each 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 | |
| 27 | To create an element instance, use the Element or SubElement factory functions. |
| 28 | |
| 29 | The :class:`ElementTree` class can be used to wrap an element structure, and |
| 30 | convert it from and to XML. |
| 31 | |
| 32 | A C implementation of this API is available as :mod:`xml.etree.cElementTree`. |
| 33 | |
| 34 | |
| 35 | .. _elementtree-functions: |
| 36 | |
| 37 | Functions |
| 38 | --------- |
| 39 | |
| 40 | |
| 41 | .. function:: Comment([text]) |
| 42 | |
| 43 | Comment element factory. This factory function creates a special element that |
| 44 | will be serialized as an XML comment. The comment string can be either an 8-bit |
| 45 | ASCII string or a Unicode string. *text* is a string containing the comment |
| 46 | string. Returns an element instance representing a comment. |
| 47 | |
| 48 | |
| 49 | .. function:: dump(elem) |
| 50 | |
| 51 | Writes an element tree or element structure to sys.stdout. This function should |
| 52 | be used for debugging only. |
| 53 | |
| 54 | The exact output format is implementation dependent. In this version, it's |
| 55 | written as an ordinary XML file. |
| 56 | |
| 57 | *elem* is an element tree or an individual element. |
| 58 | |
| 59 | |
| 60 | .. function:: Element(tag[, attrib][, **extra]) |
| 61 | |
| 62 | Element factory. This function returns an object implementing the standard |
| 63 | Element interface. The exact class or type of that object is implementation |
| 64 | dependent, but it will always be compatible with the _ElementInterface class in |
| 65 | this module. |
| 66 | |
| 67 | The element name, attribute names, and attribute values can be either 8-bit |
| 68 | ASCII strings or Unicode strings. *tag* is the element name. *attrib* is an |
| 69 | optional dictionary, containing element attributes. *extra* contains additional |
| 70 | attributes, given as keyword arguments. Returns an element instance. |
| 71 | |
| 72 | |
| 73 | .. function:: fromstring(text) |
| 74 | |
| 75 | Parses an XML section from a string constant. Same as XML. *text* is a string |
| 76 | containing XML data. Returns an Element instance. |
| 77 | |
| 78 | |
| 79 | .. function:: iselement(element) |
| 80 | |
| 81 | Checks if an object appears to be a valid element object. *element* is an |
| 82 | element instance. Returns a true value if this is an element object. |
| 83 | |
| 84 | |
| 85 | .. function:: iterparse(source[, events]) |
| 86 | |
| 87 | Parses an XML section into an element tree incrementally, and reports what's |
| 88 | going on to the user. *source* is a filename or file object containing XML data. |
| 89 | *events* is a list of events to report back. If omitted, only "end" events are |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 90 | reported. Returns an :term:`iterator` providing ``(event, elem)`` pairs. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 91 | |
| 92 | |
| 93 | .. function:: parse(source[, parser]) |
| 94 | |
| 95 | Parses an XML section into an element tree. *source* is a filename or file |
| 96 | object containing XML data. *parser* is an optional parser instance. If not |
| 97 | given, the standard XMLTreeBuilder parser is used. Returns an ElementTree |
| 98 | instance. |
| 99 | |
| 100 | |
| 101 | .. function:: ProcessingInstruction(target[, text]) |
| 102 | |
| 103 | PI element factory. This factory function creates a special element that will |
| 104 | be serialized as an XML processing instruction. *target* is a string containing |
| 105 | the PI target. *text* is a string containing the PI contents, if given. Returns |
| 106 | an element instance, representing a processing instruction. |
| 107 | |
| 108 | |
| 109 | .. function:: SubElement(parent, tag[, attrib[, **extra]]) |
| 110 | |
| 111 | Subelement factory. This function creates an element instance, and appends it |
| 112 | to an existing element. |
| 113 | |
| 114 | The element name, attribute names, and attribute values can be either 8-bit |
| 115 | ASCII strings or Unicode strings. *parent* is the parent element. *tag* is the |
| 116 | subelement name. *attrib* is an optional dictionary, containing element |
| 117 | attributes. *extra* contains additional attributes, given as keyword arguments. |
| 118 | Returns an element instance. |
| 119 | |
| 120 | |
| 121 | .. function:: tostring(element[, encoding]) |
| 122 | |
| 123 | Generates a string representation of an XML element, including all subelements. |
| 124 | *element* is an Element instance. *encoding* is the output encoding (default is |
| 125 | US-ASCII). Returns an encoded string containing the XML data. |
| 126 | |
| 127 | |
| 128 | .. function:: XML(text) |
| 129 | |
| 130 | Parses an XML section from a string constant. This function can be used to |
| 131 | embed "XML literals" in Python code. *text* is a string containing XML data. |
| 132 | Returns an Element instance. |
| 133 | |
| 134 | |
| 135 | .. function:: XMLID(text) |
| 136 | |
| 137 | Parses an XML section from a string constant, and also returns a dictionary |
| 138 | which maps from element id:s to elements. *text* is a string containing XML |
| 139 | data. Returns a tuple containing an Element instance and a dictionary. |
| 140 | |
| 141 | |
| 142 | .. _elementtree-element-interface: |
| 143 | |
| 144 | The Element Interface |
| 145 | --------------------- |
| 146 | |
| 147 | Element objects returned by Element or SubElement have the following methods |
| 148 | and attributes. |
| 149 | |
| 150 | |
| 151 | .. attribute:: Element.tag |
| 152 | |
| 153 | A string identifying what kind of data this element represents (the element |
| 154 | type, in other words). |
| 155 | |
| 156 | |
| 157 | .. attribute:: Element.text |
| 158 | |
| 159 | The *text* attribute can be used to hold additional data associated with the |
| 160 | element. As the name implies this attribute is usually a string but may be any |
| 161 | application-specific object. If the element is created from an XML file the |
| 162 | attribute will contain any text found between the element tags. |
| 163 | |
| 164 | |
| 165 | .. attribute:: Element.tail |
| 166 | |
| 167 | The *tail* attribute can be used to hold additional data associated with the |
| 168 | element. This attribute is usually a string but may be any application-specific |
| 169 | object. If the element is created from an XML file the attribute will contain |
| 170 | any text found after the element's end tag and before the next tag. |
| 171 | |
| 172 | |
| 173 | .. attribute:: Element.attrib |
| 174 | |
| 175 | A dictionary containing the element's attributes. Note that while the *attrib* |
| 176 | value is always a real mutable Python dictionary, an ElementTree implementation |
| 177 | may choose to use another internal representation, and create the dictionary |
| 178 | only if someone asks for it. To take advantage of such implementations, use the |
| 179 | dictionary methods below whenever possible. |
| 180 | |
| 181 | The following dictionary-like methods work on the element attributes. |
| 182 | |
| 183 | |
| 184 | .. method:: Element.clear() |
| 185 | |
| 186 | Resets an element. This function removes all subelements, clears all |
| 187 | attributes, and sets the text and tail attributes to None. |
| 188 | |
| 189 | |
| 190 | .. method:: Element.get(key[, default=None]) |
| 191 | |
| 192 | Gets the element attribute named *key*. |
| 193 | |
| 194 | Returns the attribute value, or *default* if the attribute was not found. |
| 195 | |
| 196 | |
| 197 | .. method:: Element.items() |
| 198 | |
| 199 | Returns the element attributes as a sequence of (name, value) pairs. The |
| 200 | attributes are returned in an arbitrary order. |
| 201 | |
| 202 | |
| 203 | .. method:: Element.keys() |
| 204 | |
| 205 | Returns the elements attribute names as a list. The names are returned in an |
| 206 | arbitrary order. |
| 207 | |
| 208 | |
| 209 | .. method:: Element.set(key, value) |
| 210 | |
| 211 | Set the attribute *key* on the element to *value*. |
| 212 | |
| 213 | The following methods work on the element's children (subelements). |
| 214 | |
| 215 | |
| 216 | .. method:: Element.append(subelement) |
| 217 | |
| 218 | Adds the element *subelement* to the end of this elements internal list of |
| 219 | subelements. |
| 220 | |
| 221 | |
| 222 | .. method:: Element.find(match) |
| 223 | |
| 224 | Finds the first subelement matching *match*. *match* may be a tag name or path. |
| 225 | Returns an element instance or ``None``. |
| 226 | |
| 227 | |
| 228 | .. method:: Element.findall(match) |
| 229 | |
| 230 | Finds all subelements matching *match*. *match* may be a tag name or path. |
| 231 | Returns an iterable yielding all matching elements in document order. |
| 232 | |
| 233 | |
| 234 | .. method:: Element.findtext(condition[, default=None]) |
| 235 | |
| 236 | Finds text for the first subelement matching *condition*. *condition* may be a |
| 237 | tag name or path. Returns the text content of the first matching element, or |
| 238 | *default* if no element was found. Note that if the matching element has no |
| 239 | text content an empty string is returned. |
| 240 | |
| 241 | |
| 242 | .. method:: Element.getchildren() |
| 243 | |
| 244 | Returns all subelements. The elements are returned in document order. |
| 245 | |
| 246 | |
| 247 | .. method:: Element.getiterator([tag=None]) |
| 248 | |
| 249 | Creates a tree iterator with the current element as the root. The iterator |
| 250 | iterates over this element and all elements below it that match the given tag. |
| 251 | If tag is ``None`` or ``'*'`` then all elements are iterated over. Returns an |
| 252 | iterable that provides element objects in document (depth first) order. |
| 253 | |
| 254 | |
| 255 | .. method:: Element.insert(index, element) |
| 256 | |
| 257 | Inserts a subelement at the given position in this element. |
| 258 | |
| 259 | |
| 260 | .. method:: Element.makeelement(tag, attrib) |
| 261 | |
| 262 | Creates a new element object of the same type as this element. Do not call this |
| 263 | method, use the SubElement factory function instead. |
| 264 | |
| 265 | |
| 266 | .. method:: Element.remove(subelement) |
| 267 | |
| 268 | Removes *subelement* from the element. Unlike the findXYZ methods this method |
| 269 | compares elements based on the instance identity, not on tag value or contents. |
| 270 | |
| 271 | Element objects also support the following sequence type methods for working |
| 272 | with subelements: :meth:`__delitem__`, :meth:`__getitem__`, :meth:`__setitem__`, |
| 273 | :meth:`__len__`. |
| 274 | |
| 275 | Caution: Because Element objects do not define a :meth:`__nonzero__` method, |
| 276 | elements with no subelements will test as ``False``. :: |
| 277 | |
| 278 | element = root.find('foo') |
| 279 | |
| 280 | if not element: # careful! |
Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 281 | print("element not found, or element has no subelements") |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 282 | |
| 283 | if element is None: |
Collin Winter | c79461b | 2007-09-01 23:34:30 +0000 | [diff] [blame] | 284 | print("element not found") |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 285 | |
| 286 | |
| 287 | .. _elementtree-elementtree-objects: |
| 288 | |
| 289 | ElementTree Objects |
| 290 | ------------------- |
| 291 | |
| 292 | |
| 293 | .. class:: ElementTree([element,] [file]) |
| 294 | |
| 295 | ElementTree wrapper class. This class represents an entire element hierarchy, |
| 296 | and adds some extra support for serialization to and from standard XML. |
| 297 | |
| 298 | *element* is the root element. The tree is initialized with the contents of the |
| 299 | XML *file* if given. |
| 300 | |
| 301 | |
| 302 | .. method:: ElementTree._setroot(element) |
| 303 | |
| 304 | Replaces the root element for this tree. This discards the current contents of |
| 305 | the tree, and replaces it with the given element. Use with care. *element* is |
| 306 | an element instance. |
| 307 | |
| 308 | |
| 309 | .. method:: ElementTree.find(path) |
| 310 | |
| 311 | Finds the first toplevel element with given tag. Same as getroot().find(path). |
| 312 | *path* is the element to look for. Returns the first matching element, or |
| 313 | ``None`` if no element was found. |
| 314 | |
| 315 | |
| 316 | .. method:: ElementTree.findall(path) |
| 317 | |
| 318 | Finds all toplevel elements with the given tag. Same as getroot().findall(path). |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 319 | *path* is the element to look for. Returns a list or :term:`iterator` containing all |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 320 | matching elements, in document order. |
| 321 | |
| 322 | |
| 323 | .. method:: ElementTree.findtext(path[, default]) |
| 324 | |
| 325 | Finds the element text for the first toplevel element with given tag. Same as |
| 326 | getroot().findtext(path). *path* is the toplevel element to look for. *default* |
| 327 | is the value to return if the element was not found. Returns the text content of |
| 328 | the first matching element, or the default value no element was found. Note |
| 329 | that if the element has is found, but has no text content, this method returns |
| 330 | an empty string. |
| 331 | |
| 332 | |
| 333 | .. method:: ElementTree.getiterator([tag]) |
| 334 | |
| 335 | Creates and returns a tree iterator for the root element. The iterator loops |
| 336 | over all elements in this tree, in section order. *tag* is the tag to look for |
| 337 | (default is to return all elements) |
| 338 | |
| 339 | |
| 340 | .. method:: ElementTree.getroot() |
| 341 | |
| 342 | Returns the root element for this tree. |
| 343 | |
| 344 | |
| 345 | .. method:: ElementTree.parse(source[, parser]) |
| 346 | |
| 347 | Loads an external XML section into this element tree. *source* is a file name or |
| 348 | file object. *parser* is an optional parser instance. If not given, the |
| 349 | standard XMLTreeBuilder parser is used. Returns the section root element. |
| 350 | |
| 351 | |
| 352 | .. method:: ElementTree.write(file[, encoding]) |
| 353 | |
| 354 | Writes the element tree to a file, as XML. *file* is a file name, or a file |
| 355 | object opened for writing. *encoding* is the output encoding (default is |
| 356 | US-ASCII). |
| 357 | |
| 358 | |
| 359 | .. _elementtree-qname-objects: |
| 360 | |
| 361 | QName Objects |
| 362 | ------------- |
| 363 | |
| 364 | |
| 365 | .. class:: QName(text_or_uri[, tag]) |
| 366 | |
| 367 | QName wrapper. This can be used to wrap a QName attribute value, in order to |
| 368 | get proper namespace handling on output. *text_or_uri* is a string containing |
| 369 | the QName value, in the form {uri}local, or, if the tag argument is given, the |
| 370 | URI part of a QName. If *tag* is given, the first argument is interpreted as an |
| 371 | URI, and this argument is interpreted as a local name. :class:`QName` instances |
| 372 | are opaque. |
| 373 | |
| 374 | |
| 375 | .. _elementtree-treebuilder-objects: |
| 376 | |
| 377 | TreeBuilder Objects |
| 378 | ------------------- |
| 379 | |
| 380 | |
| 381 | .. class:: TreeBuilder([element_factory]) |
| 382 | |
| 383 | Generic element structure builder. This builder converts a sequence of start, |
| 384 | data, and end method calls to a well-formed element structure. You can use this |
| 385 | class to build an element structure using a custom XML parser, or a parser for |
| 386 | some other XML-like format. The *element_factory* is called to create new |
| 387 | Element instances when given. |
| 388 | |
| 389 | |
| 390 | .. method:: TreeBuilder.close() |
| 391 | |
| 392 | Flushes the parser buffers, and returns the toplevel documen element. Returns an |
| 393 | Element instance. |
| 394 | |
| 395 | |
| 396 | .. method:: TreeBuilder.data(data) |
| 397 | |
| 398 | Adds text to the current element. *data* is a string. This should be either an |
| 399 | 8-bit string containing ASCII text, or a Unicode string. |
| 400 | |
| 401 | |
| 402 | .. method:: TreeBuilder.end(tag) |
| 403 | |
| 404 | Closes the current element. *tag* is the element name. Returns the closed |
| 405 | element. |
| 406 | |
| 407 | |
| 408 | .. method:: TreeBuilder.start(tag, attrs) |
| 409 | |
| 410 | Opens a new element. *tag* is the element name. *attrs* is a dictionary |
| 411 | containing element attributes. Returns the opened element. |
| 412 | |
| 413 | |
| 414 | .. _elementtree-xmltreebuilder-objects: |
| 415 | |
| 416 | XMLTreeBuilder Objects |
| 417 | ---------------------- |
| 418 | |
| 419 | |
| 420 | .. class:: XMLTreeBuilder([html,] [target]) |
| 421 | |
| 422 | Element structure builder for XML source data, based on the expat parser. *html* |
| 423 | are predefined HTML entities. This flag is not supported by the current |
| 424 | implementation. *target* is the target object. If omitted, the builder uses an |
| 425 | instance of the standard TreeBuilder class. |
| 426 | |
| 427 | |
| 428 | .. method:: XMLTreeBuilder.close() |
| 429 | |
| 430 | Finishes feeding data to the parser. Returns an element structure. |
| 431 | |
| 432 | |
| 433 | .. method:: XMLTreeBuilder.doctype(name, pubid, system) |
| 434 | |
| 435 | Handles a doctype declaration. *name* is the doctype name. *pubid* is the public |
| 436 | identifier. *system* is the system identifier. |
| 437 | |
| 438 | |
| 439 | .. method:: XMLTreeBuilder.feed(data) |
| 440 | |
| 441 | Feeds data to the parser. *data* is encoded data. |
| 442 | |