getroot
()
Returns the root element for this tree.
iter
(tag=None)
Creates and returns a tree iterator for the root element. The iterator loops over all elements in this tree, in section order. tag is the tag to look for (default is to return all elements).
iterfind
(match, namespaces=None)
Same as Element.iterfind()
, starting at the root of the tree.
New in version 3.2.
parse
(source, parser=None)
Loads an external XML section into this element tree. source is a file name or file object. parser is an optional parser instance. If not given, the standard XMLParser
parser is used. Returns the section root element.
write
(file, encoding="us-ascii", xml_declaration=None, default_namespace=None, method="xml", *, short_empty_elements=True)
Writes the element tree to a file, as XML. file is a file name, or a file object opened for writing. encoding 1 is the output encoding (default is US-ASCII). xml_declaration controls if an XML declaration should be added to the file. Use False
for never, True
for always, None
for only if not US-ASCII or UTF-8 or Unicode (default is None
). default_namespace sets the default XML namespace (for “xmlns”). method is either "xml"
, "html"
or "text"
(default is "xml"
). The keyword-only short_empty_elements parameter controls the formatting of elements that contain no content. If True
(the default), they are emitted as a single self-closed tag, otherwise they are emitted as a pair of start/end tags.
The output is either a string (str
) or binary (bytes
). This is controlled by the encoding argument. If encoding is "unicode"
, the output is a string; otherwise, it’s binary. Note that this may conflict with the type of file if it’s an open file object; make sure you do not try to write a string to a binary stream and vice versa.
New in version 3.4: The short_empty_elements parameter.
This is the XML file that is going to be manipulated:
<html>
<head>
<title>Example page</title>
</head>
<body>
<p>Moved to <a href="http://example.org/">example.org</a>
or <a href="http://example.com/">example.com</a>.</p>
</body>
</html>
Example of changing the attribute “target” of every link in first paragraph:
>>> from xml.etree.ElementTree import ElementTree
>>> tree = ElementTree()
>>> tree.parse("index.xhtml")
<Element 'html' at 0xb77e6fac>
>>> p = tree.find("body/p") # Finds first occurrence of tag p in body
>>> p
<Element 'p' at 0xb77ec26c>
>>> links = list(p.iter("a")) # Returns list of all links
>>> links
[<Element 'a' at 0xb77ec2ac>, <Element 'a' at 0xb77ec1cc>]
>>> for i in links: # Iterates through all found links
... i.attrib["target"] = "blank"
>>> tree.write("output.xhtml")