The ElementTree API (Work In Progress)
Fredrik Lundh | December 2007
This document describes the ElementTree interface.
Also see The elementtree.ElementTree Module.
The ElementTree Class #
ElementTree(element) ⇒ tree
Wraps an element in a tree object. The given element becomes the root element for this tree.
ElementTree() ⇒ tree
Same, but creates an empty tree. The root element is set to None. Use parse or _setroot to set the root.
ElementTree(file=source) ⇒ tree
Same, but loads an XML document into the tree. This is the same thing as creating an empty tree and calling the parse method on it:
tree = ET.ElementTree() tree.parse(source)
Alternatively, you can use the parse function to create a tree and load it in one step.
tree = ET.parse(source)
Methods #
parse #
tree.parse(source) ⇒ element
Loads an external XML document into this tree. The original contents are discarded. The source can be either a file name or a file object, or any other object that implements a file-like read method.
This method returns the root element.
tree.parse(source, parser) ⇒ element
Same, but uses the given parser object.
iter #
getiterator #
find #
findall #
findtext #
write #
tree.write(file)
tree.write(file, options)
Writes the tree to an XML file. The file can be either a name, or a file object, or any other object that has a file-like write method.
tree.write(file, encoding)
(Deprecated) Same, with the encoding given as a positional argument instead of a keyword option. This syntax is not portable, and should be avoided in new code.
Options
Use keyword arguments to provide options to the method:
encoding= Output encoding. If omitted or set to None, defaults to US-ASCII. The current ElementTree implementation only supports ASCII-compatible encodings (e.g. ISO-8859-1, UTF-8, and other encodings where the first 128 characters are identical to US-ASCII).
method= (New in 1.3) Output format. One of “xml”, “html” for HTML serialization (special treatment of empty elements and script/style elements), “text” (text and tail content only), and “c14n” (canonicalized output). If omitted or set to None, it defaults to “xml”.
xml_declaration= (New in 1.3) If True, always outputs an XML declaration. If False, never outputs an XML declaration. If omitted or None, only outputs a declaration if the encoding is neither US-ASCII nor UTF-8. In ElementTree 1.2, this option is hard-wired to None.
default_namespace= (New in 1.3) Specifies the default namespace to use for this file (an URI). If omitted, all namespaces gets distinct prefixes (usually “ns” plus a number).
In the current alpha, this only works if all elements in the tree belongs to a namespace.
write_c14n #
tree.write_c14n(file)
(New in 1.3) An alias for calling write with the method option set to “c14n”. Using the write method is preferred.
getroot #
tree.getroot() ⇒ element
Fetches the root element.
_setroot #
tree._setroot(element)
Replaces the root element. The old content is discarded.
