summaryrefslogtreecommitdiff
path: root/devdocs/python~3.12/library%2Fxml.etree.elementtree.html
diff options
context:
space:
mode:
authorCraig Jennings <c@cjennings.net>2024-04-07 13:41:34 -0500
committerCraig Jennings <c@cjennings.net>2024-04-07 13:41:34 -0500
commit754bbf7a25a8dda49b5d08ef0d0443bbf5af0e36 (patch)
treef1190704f78f04a2b0b4c977d20fe96a828377f1 /devdocs/python~3.12/library%2Fxml.etree.elementtree.html
new repository
Diffstat (limited to 'devdocs/python~3.12/library%2Fxml.etree.elementtree.html')
-rw-r--r--devdocs/python~3.12/library%2Fxml.etree.elementtree.html541
1 files changed, 541 insertions, 0 deletions
diff --git a/devdocs/python~3.12/library%2Fxml.etree.elementtree.html b/devdocs/python~3.12/library%2Fxml.etree.elementtree.html
new file mode 100644
index 00000000..936b73da
--- /dev/null
+++ b/devdocs/python~3.12/library%2Fxml.etree.elementtree.html
@@ -0,0 +1,541 @@
+ <span id="xml-etree-elementtree-the-elementtree-xml-api"></span><h1>xml.etree.ElementTree — The ElementTree XML API</h1> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/xml/etree/ElementTree.py">Lib/xml/etree/ElementTree.py</a></p> <p>The <a class="reference internal" href="#module-xml.etree.ElementTree" title="xml.etree.ElementTree: Implementation of the ElementTree API."><code>xml.etree.ElementTree</code></a> module implements a simple and efficient API for parsing and creating XML data.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.3: </span>This module will use a fast implementation whenever available.</p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.3: </span>The <code>xml.etree.cElementTree</code> module is deprecated.</p> </div> <div class="admonition warning"> <p class="admonition-title">Warning</p> <p>The <a class="reference internal" href="#module-xml.etree.ElementTree" title="xml.etree.ElementTree: Implementation of the ElementTree API."><code>xml.etree.ElementTree</code></a> module is not secure against maliciously constructed data. If you need to parse untrusted or unauthenticated data see <a class="reference internal" href="xml#xml-vulnerabilities"><span class="std std-ref">XML vulnerabilities</span></a>.</p> </div> <section id="tutorial"> <h2>Tutorial</h2> <p>This is a short tutorial for using <a class="reference internal" href="#module-xml.etree.ElementTree" title="xml.etree.ElementTree: Implementation of the ElementTree API."><code>xml.etree.ElementTree</code></a> (<code>ET</code> in short). The goal is to demonstrate some of the building blocks and basic concepts of the module.</p> <section id="xml-tree-and-elements"> <h3>XML tree and elements</h3> <p>XML is an inherently hierarchical data format, and the most natural way to represent it is with a tree. <code>ET</code> has two classes for this purpose - <a class="reference internal" href="#xml.etree.ElementTree.ElementTree" title="xml.etree.ElementTree.ElementTree"><code>ElementTree</code></a> represents the whole XML document as a tree, and <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code>Element</code></a> represents a single node in this tree. Interactions with the whole document (reading and writing to/from files) are usually done on the <a class="reference internal" href="#xml.etree.ElementTree.ElementTree" title="xml.etree.ElementTree.ElementTree"><code>ElementTree</code></a> level. Interactions with a single XML element and its sub-elements are done on the <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code>Element</code></a> level.</p> </section> <section id="parsing-xml"> <span id="elementtree-parsing-xml"></span><h3>Parsing XML</h3> <p>We’ll be using the following XML document as the sample data for this section:</p> <pre data-language="xml">&lt;?xml version="1.0"?&gt;
+&lt;data&gt;
+ &lt;country name="Liechtenstein"&gt;
+ &lt;rank&gt;1&lt;/rank&gt;
+ &lt;year&gt;2008&lt;/year&gt;
+ &lt;gdppc&gt;141100&lt;/gdppc&gt;
+ &lt;neighbor name="Austria" direction="E"/&gt;
+ &lt;neighbor name="Switzerland" direction="W"/&gt;
+ &lt;/country&gt;
+ &lt;country name="Singapore"&gt;
+ &lt;rank&gt;4&lt;/rank&gt;
+ &lt;year&gt;2011&lt;/year&gt;
+ &lt;gdppc&gt;59900&lt;/gdppc&gt;
+ &lt;neighbor name="Malaysia" direction="N"/&gt;
+ &lt;/country&gt;
+ &lt;country name="Panama"&gt;
+ &lt;rank&gt;68&lt;/rank&gt;
+ &lt;year&gt;2011&lt;/year&gt;
+ &lt;gdppc&gt;13600&lt;/gdppc&gt;
+ &lt;neighbor name="Costa Rica" direction="W"/&gt;
+ &lt;neighbor name="Colombia" direction="E"/&gt;
+ &lt;/country&gt;
+&lt;/data&gt;
+</pre> <p>We can import this data by reading from a file:</p> <pre data-language="python">import xml.etree.ElementTree as ET
+tree = ET.parse('country_data.xml')
+root = tree.getroot()
+</pre> <p>Or directly from a string:</p> <pre data-language="python">root = ET.fromstring(country_data_as_string)
+</pre> <p><a class="reference internal" href="#xml.etree.ElementTree.fromstring" title="xml.etree.ElementTree.fromstring"><code>fromstring()</code></a> parses XML from a string directly into an <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code>Element</code></a>, which is the root element of the parsed tree. Other parsing functions may create an <a class="reference internal" href="#xml.etree.ElementTree.ElementTree" title="xml.etree.ElementTree.ElementTree"><code>ElementTree</code></a>. Check the documentation to be sure.</p> <p>As an <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code>Element</code></a>, <code>root</code> has a tag and a dictionary of attributes:</p> <pre data-language="python">&gt;&gt;&gt; root.tag
+'data'
+&gt;&gt;&gt; root.attrib
+{}
+</pre> <p>It also has children nodes over which we can iterate:</p> <pre data-language="python">&gt;&gt;&gt; for child in root:
+... print(child.tag, child.attrib)
+...
+country {'name': 'Liechtenstein'}
+country {'name': 'Singapore'}
+country {'name': 'Panama'}
+</pre> <p>Children are nested, and we can access specific child nodes by index:</p> <pre data-language="python">&gt;&gt;&gt; root[0][1].text
+'2008'
+</pre> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Not all elements of the XML input will end up as elements of the parsed tree. Currently, this module skips over any XML comments, processing instructions, and document type declarations in the input. Nevertheless, trees built using this module’s API rather than parsing from XML text can have comments and processing instructions in them; they will be included when generating XML output. A document type declaration may be accessed by passing a custom <a class="reference internal" href="#xml.etree.ElementTree.TreeBuilder" title="xml.etree.ElementTree.TreeBuilder"><code>TreeBuilder</code></a> instance to the <a class="reference internal" href="#xml.etree.ElementTree.XMLParser" title="xml.etree.ElementTree.XMLParser"><code>XMLParser</code></a> constructor.</p> </div> </section> <section id="pull-api-for-non-blocking-parsing"> <span id="elementtree-pull-parsing"></span><h3>Pull API for non-blocking parsing</h3> <p>Most parsing functions provided by this module require the whole document to be read at once before returning any result. It is possible to use an <a class="reference internal" href="#xml.etree.ElementTree.XMLParser" title="xml.etree.ElementTree.XMLParser"><code>XMLParser</code></a> and feed data into it incrementally, but it is a push API that calls methods on a callback target, which is too low-level and inconvenient for most needs. Sometimes what the user really wants is to be able to parse XML incrementally, without blocking operations, while enjoying the convenience of fully constructed <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code>Element</code></a> objects.</p> <p>The most powerful tool for doing this is <a class="reference internal" href="#xml.etree.ElementTree.XMLPullParser" title="xml.etree.ElementTree.XMLPullParser"><code>XMLPullParser</code></a>. It does not require a blocking read to obtain the XML data, and is instead fed with data incrementally with <a class="reference internal" href="#xml.etree.ElementTree.XMLPullParser.feed" title="xml.etree.ElementTree.XMLPullParser.feed"><code>XMLPullParser.feed()</code></a> calls. To get the parsed XML elements, call <a class="reference internal" href="#xml.etree.ElementTree.XMLPullParser.read_events" title="xml.etree.ElementTree.XMLPullParser.read_events"><code>XMLPullParser.read_events()</code></a>. Here is an example:</p> <pre data-language="python">&gt;&gt;&gt; parser = ET.XMLPullParser(['start', 'end'])
+&gt;&gt;&gt; parser.feed('&lt;mytag&gt;sometext')
+&gt;&gt;&gt; list(parser.read_events())
+[('start', &lt;Element 'mytag' at 0x7fa66db2be58&gt;)]
+&gt;&gt;&gt; parser.feed(' more text&lt;/mytag&gt;')
+&gt;&gt;&gt; for event, elem in parser.read_events():
+... print(event)
+... print(elem.tag, 'text=', elem.text)
+...
+end
+mytag text= sometext more text
+</pre> <p>The obvious use case is applications that operate in a non-blocking fashion where the XML data is being received from a socket or read incrementally from some storage device. In such cases, blocking reads are unacceptable.</p> <p>Because it’s so flexible, <a class="reference internal" href="#xml.etree.ElementTree.XMLPullParser" title="xml.etree.ElementTree.XMLPullParser"><code>XMLPullParser</code></a> can be inconvenient to use for simpler use-cases. If you don’t mind your application blocking on reading XML data but would still like to have incremental parsing capabilities, take a look at <a class="reference internal" href="#xml.etree.ElementTree.iterparse" title="xml.etree.ElementTree.iterparse"><code>iterparse()</code></a>. It can be useful when you’re reading a large XML document and don’t want to hold it wholly in memory.</p> </section> <section id="finding-interesting-elements"> <h3>Finding interesting elements</h3> <p><a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code>Element</code></a> has some useful methods that help iterate recursively over all the sub-tree below it (its children, their children, and so on). For example, <a class="reference internal" href="#xml.etree.ElementTree.Element.iter" title="xml.etree.ElementTree.Element.iter"><code>Element.iter()</code></a>:</p> <pre data-language="python">&gt;&gt;&gt; for neighbor in root.iter('neighbor'):
+... print(neighbor.attrib)
+...
+{'name': 'Austria', 'direction': 'E'}
+{'name': 'Switzerland', 'direction': 'W'}
+{'name': 'Malaysia', 'direction': 'N'}
+{'name': 'Costa Rica', 'direction': 'W'}
+{'name': 'Colombia', 'direction': 'E'}
+</pre> <p><a class="reference internal" href="#xml.etree.ElementTree.Element.findall" title="xml.etree.ElementTree.Element.findall"><code>Element.findall()</code></a> finds only elements with a tag which are direct children of the current element. <a class="reference internal" href="#xml.etree.ElementTree.Element.find" title="xml.etree.ElementTree.Element.find"><code>Element.find()</code></a> finds the <em>first</em> child with a particular tag, and <a class="reference internal" href="#xml.etree.ElementTree.Element.text" title="xml.etree.ElementTree.Element.text"><code>Element.text</code></a> accesses the element’s text content. <a class="reference internal" href="#xml.etree.ElementTree.Element.get" title="xml.etree.ElementTree.Element.get"><code>Element.get()</code></a> accesses the element’s attributes:</p> <pre data-language="python">&gt;&gt;&gt; for country in root.findall('country'):
+... rank = country.find('rank').text
+... name = country.get('name')
+... print(name, rank)
+...
+Liechtenstein 1
+Singapore 4
+Panama 68
+</pre> <p>More sophisticated specification of which elements to look for is possible by using <a class="reference internal" href="#elementtree-xpath"><span class="std std-ref">XPath</span></a>.</p> </section> <section id="modifying-an-xml-file"> <h3>Modifying an XML File</h3> <p><a class="reference internal" href="#xml.etree.ElementTree.ElementTree" title="xml.etree.ElementTree.ElementTree"><code>ElementTree</code></a> provides a simple way to build XML documents and write them to files. The <a class="reference internal" href="#xml.etree.ElementTree.ElementTree.write" title="xml.etree.ElementTree.ElementTree.write"><code>ElementTree.write()</code></a> method serves this purpose.</p> <p>Once created, an <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code>Element</code></a> object may be manipulated by directly changing its fields (such as <a class="reference internal" href="#xml.etree.ElementTree.Element.text" title="xml.etree.ElementTree.Element.text"><code>Element.text</code></a>), adding and modifying attributes (<a class="reference internal" href="#xml.etree.ElementTree.Element.set" title="xml.etree.ElementTree.Element.set"><code>Element.set()</code></a> method), as well as adding new children (for example with <a class="reference internal" href="#xml.etree.ElementTree.Element.append" title="xml.etree.ElementTree.Element.append"><code>Element.append()</code></a>).</p> <p>Let’s say we want to add one to each country’s rank, and add an <code>updated</code> attribute to the rank element:</p> <pre data-language="python">&gt;&gt;&gt; for rank in root.iter('rank'):
+... new_rank = int(rank.text) + 1
+... rank.text = str(new_rank)
+... rank.set('updated', 'yes')
+...
+&gt;&gt;&gt; tree.write('output.xml')
+</pre> <p>Our XML now looks like this:</p> <pre data-language="xml">&lt;?xml version="1.0"?&gt;
+&lt;data&gt;
+ &lt;country name="Liechtenstein"&gt;
+ &lt;rank updated="yes"&gt;2&lt;/rank&gt;
+ &lt;year&gt;2008&lt;/year&gt;
+ &lt;gdppc&gt;141100&lt;/gdppc&gt;
+ &lt;neighbor name="Austria" direction="E"/&gt;
+ &lt;neighbor name="Switzerland" direction="W"/&gt;
+ &lt;/country&gt;
+ &lt;country name="Singapore"&gt;
+ &lt;rank updated="yes"&gt;5&lt;/rank&gt;
+ &lt;year&gt;2011&lt;/year&gt;
+ &lt;gdppc&gt;59900&lt;/gdppc&gt;
+ &lt;neighbor name="Malaysia" direction="N"/&gt;
+ &lt;/country&gt;
+ &lt;country name="Panama"&gt;
+ &lt;rank updated="yes"&gt;69&lt;/rank&gt;
+ &lt;year&gt;2011&lt;/year&gt;
+ &lt;gdppc&gt;13600&lt;/gdppc&gt;
+ &lt;neighbor name="Costa Rica" direction="W"/&gt;
+ &lt;neighbor name="Colombia" direction="E"/&gt;
+ &lt;/country&gt;
+&lt;/data&gt;
+</pre> <p>We can remove elements using <a class="reference internal" href="#xml.etree.ElementTree.Element.remove" title="xml.etree.ElementTree.Element.remove"><code>Element.remove()</code></a>. Let’s say we want to remove all countries with a rank higher than 50:</p> <pre data-language="python">&gt;&gt;&gt; for country in root.findall('country'):
+... # using root.findall() to avoid removal during traversal
+... rank = int(country.find('rank').text)
+... if rank &gt; 50:
+... root.remove(country)
+...
+&gt;&gt;&gt; tree.write('output.xml')
+</pre> <p>Note that concurrent modification while iterating can lead to problems, just like when iterating and modifying Python lists or dicts. Therefore, the example first collects all matching elements with <code>root.findall()</code>, and only then iterates over the list of matches.</p> <p>Our XML now looks like this:</p> <pre data-language="xml">&lt;?xml version="1.0"?&gt;
+&lt;data&gt;
+ &lt;country name="Liechtenstein"&gt;
+ &lt;rank updated="yes"&gt;2&lt;/rank&gt;
+ &lt;year&gt;2008&lt;/year&gt;
+ &lt;gdppc&gt;141100&lt;/gdppc&gt;
+ &lt;neighbor name="Austria" direction="E"/&gt;
+ &lt;neighbor name="Switzerland" direction="W"/&gt;
+ &lt;/country&gt;
+ &lt;country name="Singapore"&gt;
+ &lt;rank updated="yes"&gt;5&lt;/rank&gt;
+ &lt;year&gt;2011&lt;/year&gt;
+ &lt;gdppc&gt;59900&lt;/gdppc&gt;
+ &lt;neighbor name="Malaysia" direction="N"/&gt;
+ &lt;/country&gt;
+&lt;/data&gt;
+</pre> </section> <section id="building-xml-documents"> <h3>Building XML documents</h3> <p>The <a class="reference internal" href="#xml.etree.ElementTree.SubElement" title="xml.etree.ElementTree.SubElement"><code>SubElement()</code></a> function also provides a convenient way to create new sub-elements for a given element:</p> <pre data-language="python">&gt;&gt;&gt; a = ET.Element('a')
+&gt;&gt;&gt; b = ET.SubElement(a, 'b')
+&gt;&gt;&gt; c = ET.SubElement(a, 'c')
+&gt;&gt;&gt; d = ET.SubElement(c, 'd')
+&gt;&gt;&gt; ET.dump(a)
+&lt;a&gt;&lt;b /&gt;&lt;c&gt;&lt;d /&gt;&lt;/c&gt;&lt;/a&gt;
+</pre> </section> <section id="parsing-xml-with-namespaces"> <h3>Parsing XML with Namespaces</h3> <p>If the XML input has <a class="reference external" href="https://en.wikipedia.org/wiki/XML_namespace">namespaces</a>, tags and attributes with prefixes in the form <code>prefix:sometag</code> get expanded to <code>{uri}sometag</code> where the <em>prefix</em> is replaced by the full <em>URI</em>. Also, if there is a <a class="reference external" href="https://www.w3.org/TR/xml-names/#defaulting">default namespace</a>, that full URI gets prepended to all of the non-prefixed tags.</p> <p>Here is an XML example that incorporates two namespaces, one with the prefix “fictional” and the other serving as the default namespace:</p> <pre data-language="xml">&lt;?xml version="1.0"?&gt;
+&lt;actors xmlns:fictional="http://characters.example.com"
+ xmlns="http://people.example.com"&gt;
+ &lt;actor&gt;
+ &lt;name&gt;John Cleese&lt;/name&gt;
+ &lt;fictional:character&gt;Lancelot&lt;/fictional:character&gt;
+ &lt;fictional:character&gt;Archie Leach&lt;/fictional:character&gt;
+ &lt;/actor&gt;
+ &lt;actor&gt;
+ &lt;name&gt;Eric Idle&lt;/name&gt;
+ &lt;fictional:character&gt;Sir Robin&lt;/fictional:character&gt;
+ &lt;fictional:character&gt;Gunther&lt;/fictional:character&gt;
+ &lt;fictional:character&gt;Commander Clement&lt;/fictional:character&gt;
+ &lt;/actor&gt;
+&lt;/actors&gt;
+</pre> <p>One way to search and explore this XML example is to manually add the URI to every tag or attribute in the xpath of a <a class="reference internal" href="#xml.etree.ElementTree.Element.find" title="xml.etree.ElementTree.Element.find"><code>find()</code></a> or <a class="reference internal" href="#xml.etree.ElementTree.Element.findall" title="xml.etree.ElementTree.Element.findall"><code>findall()</code></a>:</p> <pre data-language="python">root = fromstring(xml_text)
+for actor in root.findall('{http://people.example.com}actor'):
+ name = actor.find('{http://people.example.com}name')
+ print(name.text)
+ for char in actor.findall('{http://characters.example.com}character'):
+ print(' |--&gt;', char.text)
+</pre> <p>A better way to search the namespaced XML example is to create a dictionary with your own prefixes and use those in the search functions:</p> <pre data-language="python">ns = {'real_person': 'http://people.example.com',
+ 'role': 'http://characters.example.com'}
+
+for actor in root.findall('real_person:actor', ns):
+ name = actor.find('real_person:name', ns)
+ print(name.text)
+ for char in actor.findall('role:character', ns):
+ print(' |--&gt;', char.text)
+</pre> <p>These two approaches both output:</p> <pre data-language="python">John Cleese
+ |--&gt; Lancelot
+ |--&gt; Archie Leach
+Eric Idle
+ |--&gt; Sir Robin
+ |--&gt; Gunther
+ |--&gt; Commander Clement
+</pre> </section> </section> <section id="xpath-support"> <span id="elementtree-xpath"></span><h2>XPath support</h2> <p>This module provides limited support for <a class="reference external" href="https://www.w3.org/TR/xpath">XPath expressions</a> for locating elements in a tree. The goal is to support a small subset of the abbreviated syntax; a full XPath engine is outside the scope of the module.</p> <section id="example"> <h3>Example</h3> <p>Here’s an example that demonstrates some of the XPath capabilities of the module. We’ll be using the <code>countrydata</code> XML document from the <a class="reference internal" href="#elementtree-parsing-xml"><span class="std std-ref">Parsing XML</span></a> section:</p> <pre data-language="python">import xml.etree.ElementTree as ET
+
+root = ET.fromstring(countrydata)
+
+# Top-level elements
+root.findall(".")
+
+# All 'neighbor' grand-children of 'country' children of the top-level
+# elements
+root.findall("./country/neighbor")
+
+# Nodes with name='Singapore' that have a 'year' child
+root.findall(".//year/..[@name='Singapore']")
+
+# 'year' nodes that are children of nodes with name='Singapore'
+root.findall(".//*[@name='Singapore']/year")
+
+# All 'neighbor' nodes that are the second child of their parent
+root.findall(".//neighbor[2]")
+</pre> <p>For XML with namespaces, use the usual qualified <code>{namespace}tag</code> notation:</p> <pre data-language="python"># All dublin-core "title" tags in the document
+root.findall(".//{http://purl.org/dc/elements/1.1/}title")
+</pre> </section> <section id="supported-xpath-syntax"> <h3>Supported XPath syntax</h3> <table class="docutils align-default"> <thead> <tr>
+<th class="head"><p>Syntax</p></th> <th class="head"><p>Meaning</p></th> </tr> </thead> <tr>
+<td><p><code>tag</code></p></td> <td>
+<p>Selects all child elements with the given tag. For example, <code>spam</code> selects all child elements named <code>spam</code>, and <code>spam/egg</code> selects all grandchildren named <code>egg</code> in all children named <code>spam</code>. <code>{namespace}*</code> selects all tags in the given namespace, <code>{*}spam</code> selects tags named <code>spam</code> in any (or no) namespace, and <code>{}*</code> only selects tags that are not in a namespace.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>Support for star-wildcards was added.</p> </div> </td> </tr> <tr>
+<td><p><code>*</code></p></td> <td><p>Selects all child elements, including comments and processing instructions. For example, <code>*/egg</code> selects all grandchildren named <code>egg</code>.</p></td> </tr> <tr>
+<td><p><code>.</code></p></td> <td><p>Selects the current node. This is mostly useful at the beginning of the path, to indicate that it’s a relative path.</p></td> </tr> <tr>
+<td><p><code>//</code></p></td> <td><p>Selects all subelements, on all levels beneath the current element. For example, <code>.//egg</code> selects all <code>egg</code> elements in the entire tree.</p></td> </tr> <tr>
+<td><p><code>..</code></p></td> <td><p>Selects the parent element. Returns <code>None</code> if the path attempts to reach the ancestors of the start element (the element <code>find</code> was called on).</p></td> </tr> <tr>
+<td><p><code>[@attrib]</code></p></td> <td><p>Selects all elements that have the given attribute.</p></td> </tr> <tr>
+<td><p><code>[@attrib='value']</code></p></td> <td><p>Selects all elements for which the given attribute has the given value. The value cannot contain quotes.</p></td> </tr> <tr>
+<td><p><code>[@attrib!='value']</code></p></td> <td>
+<p>Selects all elements for which the given attribute does not have the given value. The value cannot contain quotes.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.10.</span></p> </div> </td> </tr> <tr>
+<td><p><code>[tag]</code></p></td> <td><p>Selects all elements that have a child named <code>tag</code>. Only immediate children are supported.</p></td> </tr> <tr>
+<td><p><code>[.='text']</code></p></td> <td>
+<p>Selects all elements whose complete text content, including descendants, equals the given <code>text</code>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> </td> </tr> <tr>
+<td><p><code>[.!='text']</code></p></td> <td>
+<p>Selects all elements whose complete text content, including descendants, does not equal the given <code>text</code>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.10.</span></p> </div> </td> </tr> <tr>
+<td><p><code>[tag='text']</code></p></td> <td><p>Selects all elements that have a child named <code>tag</code> whose complete text content, including descendants, equals the given <code>text</code>.</p></td> </tr> <tr>
+<td><p><code>[tag!='text']</code></p></td> <td>
+<p>Selects all elements that have a child named <code>tag</code> whose complete text content, including descendants, does not equal the given <code>text</code>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.10.</span></p> </div> </td> </tr> <tr>
+<td><p><code>[position]</code></p></td> <td><p>Selects all elements that are located at the given position. The position can be either an integer (1 is the first position), the expression <code>last()</code> (for the last position), or a position relative to the last position (e.g. <code>last()-1</code>).</p></td> </tr> </table> <p>Predicates (expressions within square brackets) must be preceded by a tag name, an asterisk, or another predicate. <code>position</code> predicates must be preceded by a tag name.</p> </section> </section> <section id="reference"> <h2>Reference</h2> <section id="functions"> <span id="elementtree-functions"></span><h3>Functions</h3> <dl class="py function"> <dt class="sig sig-object py" id="xml.etree.ElementTree.canonicalize">
+<code>xml.etree.ElementTree.canonicalize(xml_data=None, *, out=None, from_file=None, **options)</code> </dt> <dd>
+<p><a class="reference external" href="https://www.w3.org/TR/xml-c14n2/">C14N 2.0</a> transformation function.</p> <p>Canonicalization is a way to normalise XML output in a way that allows byte-by-byte comparisons and digital signatures. It reduced the freedom that XML serializers have and instead generates a more constrained XML representation. The main restrictions regard the placement of namespace declarations, the ordering of attributes, and ignorable whitespace.</p> <p>This function takes an XML data string (<em>xml_data</em>) or a file path or file-like object (<em>from_file</em>) as input, converts it to the canonical form, and writes it out using the <em>out</em> file(-like) object, if provided, or returns it as a text string if not. The output file receives text, not bytes. It should therefore be opened in text mode with <code>utf-8</code> encoding.</p> <p>Typical uses:</p> <pre data-language="python">xml_data = "&lt;root&gt;...&lt;/root&gt;"
+print(canonicalize(xml_data))
+
+with open("c14n_output.xml", mode='w', encoding='utf-8') as out_file:
+ canonicalize(xml_data, out=out_file)
+
+with open("c14n_output.xml", mode='w', encoding='utf-8') as out_file:
+ canonicalize(from_file="inputfile.xml", out=out_file)
+</pre> <p>The configuration <em>options</em> are as follows:</p> <ul class="simple"> <li>
+<em>with_comments</em>: set to true to include comments (default: false)</li> <li>
+<dl class="simple"> <dt>
+<em>strip_text</em>: set to true to strip whitespace before and after text content</dt>
+<dd>
+<p>(default: false)</p> </dd> </dl> </li> <li>
+<dl class="simple"> <dt>
+<em>rewrite_prefixes</em>: set to true to replace namespace prefixes by “n{number}”</dt>
+<dd>
+<p>(default: false)</p> </dd> </dl> </li> <li>
+<dl class="simple"> <dt>
+<em>qname_aware_tags</em>: a set of qname aware tag names in which prefixes</dt>
+<dd>
+<p>should be replaced in text content (default: empty)</p> </dd> </dl> </li> <li>
+<dl class="simple"> <dt>
+<em>qname_aware_attrs</em>: a set of qname aware attribute names in which prefixes</dt>
+<dd>
+<p>should be replaced in text content (default: empty)</p> </dd> </dl> </li> <li>
+<em>exclude_attrs</em>: a set of attribute names that should not be serialised</li> <li>
+<em>exclude_tags</em>: a set of tag names that should not be serialised</li> </ul> <p>In the option list above, “a set” refers to any collection or iterable of strings, no ordering is expected.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="xml.etree.ElementTree.Comment">
+<code>xml.etree.ElementTree.Comment(text=None)</code> </dt> <dd>
+<p>Comment element factory. This factory function creates a special element that will be serialized as an XML comment by the standard serializer. The comment string can be either a bytestring or a Unicode string. <em>text</em> is a string containing the comment string. Returns an element instance representing a comment.</p> <p>Note that <a class="reference internal" href="#xml.etree.ElementTree.XMLParser" title="xml.etree.ElementTree.XMLParser"><code>XMLParser</code></a> skips over comments in the input instead of creating comment objects for them. An <a class="reference internal" href="#xml.etree.ElementTree.ElementTree" title="xml.etree.ElementTree.ElementTree"><code>ElementTree</code></a> will only contain comment nodes if they have been inserted into to the tree using one of the <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code>Element</code></a> methods.</p> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="xml.etree.ElementTree.dump">
+<code>xml.etree.ElementTree.dump(elem)</code> </dt> <dd>
+<p>Writes an element tree or element structure to sys.stdout. This function should be used for debugging only.</p> <p>The exact output format is implementation dependent. In this version, it’s written as an ordinary XML file.</p> <p><em>elem</em> is an element tree or an individual element.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>The <a class="reference internal" href="#xml.etree.ElementTree.dump" title="xml.etree.ElementTree.dump"><code>dump()</code></a> function now preserves the attribute order specified by the user.</p> </div> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="xml.etree.ElementTree.fromstring">
+<code>xml.etree.ElementTree.fromstring(text, parser=None)</code> </dt> <dd>
+<p>Parses an XML section from a string constant. Same as <a class="reference internal" href="#xml.etree.ElementTree.XML" title="xml.etree.ElementTree.XML"><code>XML()</code></a>. <em>text</em> is a string containing XML data. <em>parser</em> is an optional parser instance. If not given, the standard <a class="reference internal" href="#xml.etree.ElementTree.XMLParser" title="xml.etree.ElementTree.XMLParser"><code>XMLParser</code></a> parser is used. Returns an <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code>Element</code></a> instance.</p> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="xml.etree.ElementTree.fromstringlist">
+<code>xml.etree.ElementTree.fromstringlist(sequence, parser=None)</code> </dt> <dd>
+<p>Parses an XML document from a sequence of string fragments. <em>sequence</em> is a list or other sequence containing XML data fragments. <em>parser</em> is an optional parser instance. If not given, the standard <a class="reference internal" href="#xml.etree.ElementTree.XMLParser" title="xml.etree.ElementTree.XMLParser"><code>XMLParser</code></a> parser is used. Returns an <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code>Element</code></a> instance.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="xml.etree.ElementTree.indent">
+<code>xml.etree.ElementTree.indent(tree, space=' ', level=0)</code> </dt> <dd>
+<p>Appends whitespace to the subtree to indent the tree visually. This can be used to generate pretty-printed XML output. <em>tree</em> can be an Element or ElementTree. <em>space</em> is the whitespace string that will be inserted for each indentation level, two space characters by default. For indenting partial subtrees inside of an already indented tree, pass the initial indentation level as <em>level</em>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.9.</span></p> </div> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="xml.etree.ElementTree.iselement">
+<code>xml.etree.ElementTree.iselement(element)</code> </dt> <dd>
+<p>Check if an object appears to be a valid element object. <em>element</em> is an element instance. Return <code>True</code> if this is an element object.</p> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="xml.etree.ElementTree.iterparse">
+<code>xml.etree.ElementTree.iterparse(source, events=None, parser=None)</code> </dt> <dd>
+<p>Parses an XML section into an element tree incrementally, and reports what’s going on to the user. <em>source</em> is a filename or <a class="reference internal" href="../glossary#term-file-object"><span class="xref std std-term">file object</span></a> containing XML data. <em>events</em> is a sequence of events to report back. The supported events are the strings <code>"start"</code>, <code>"end"</code>, <code>"comment"</code>, <code>"pi"</code>, <code>"start-ns"</code> and <code>"end-ns"</code> (the “ns” events are used to get detailed namespace information). If <em>events</em> is omitted, only <code>"end"</code> events are reported. <em>parser</em> is an optional parser instance. If not given, the standard <a class="reference internal" href="#xml.etree.ElementTree.XMLParser" title="xml.etree.ElementTree.XMLParser"><code>XMLParser</code></a> parser is used. <em>parser</em> must be a subclass of <a class="reference internal" href="#xml.etree.ElementTree.XMLParser" title="xml.etree.ElementTree.XMLParser"><code>XMLParser</code></a> and can only use the default <a class="reference internal" href="#xml.etree.ElementTree.TreeBuilder" title="xml.etree.ElementTree.TreeBuilder"><code>TreeBuilder</code></a> as a target. Returns an <a class="reference internal" href="../glossary#term-iterator"><span class="xref std std-term">iterator</span></a> providing <code>(event, elem)</code> pairs; it has a <code>root</code> attribute that references the root element of the resulting XML tree once <em>source</em> is fully read.</p> <p>Note that while <a class="reference internal" href="#xml.etree.ElementTree.iterparse" title="xml.etree.ElementTree.iterparse"><code>iterparse()</code></a> builds the tree incrementally, it issues blocking reads on <em>source</em> (or the file it names). As such, it’s unsuitable for applications where blocking reads can’t be made. For fully non-blocking parsing, see <a class="reference internal" href="#xml.etree.ElementTree.XMLPullParser" title="xml.etree.ElementTree.XMLPullParser"><code>XMLPullParser</code></a>.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p><a class="reference internal" href="#xml.etree.ElementTree.iterparse" title="xml.etree.ElementTree.iterparse"><code>iterparse()</code></a> only guarantees that it has seen the “&gt;” character of a starting tag when it emits a “start” event, so the attributes are defined, but the contents of the text and tail attributes are undefined at that point. The same applies to the element children; they may or may not be present.</p> <p>If you need a fully populated element, look for “end” events instead.</p> </div> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.4: </span>The <em>parser</em> argument.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>The <code>comment</code> and <code>pi</code> events were added.</p> </div> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="xml.etree.ElementTree.parse">
+<code>xml.etree.ElementTree.parse(source, parser=None)</code> </dt> <dd>
+<p>Parses an XML section into an element tree. <em>source</em> is a filename or file object containing XML data. <em>parser</em> is an optional parser instance. If not given, the standard <a class="reference internal" href="#xml.etree.ElementTree.XMLParser" title="xml.etree.ElementTree.XMLParser"><code>XMLParser</code></a> parser is used. Returns an <a class="reference internal" href="#xml.etree.ElementTree.ElementTree" title="xml.etree.ElementTree.ElementTree"><code>ElementTree</code></a> instance.</p> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="xml.etree.ElementTree.ProcessingInstruction">
+<code>xml.etree.ElementTree.ProcessingInstruction(target, text=None)</code> </dt> <dd>
+<p>PI element factory. This factory function creates a special element that will be serialized as an XML processing instruction. <em>target</em> is a string containing the PI target. <em>text</em> is a string containing the PI contents, if given. Returns an element instance, representing a processing instruction.</p> <p>Note that <a class="reference internal" href="#xml.etree.ElementTree.XMLParser" title="xml.etree.ElementTree.XMLParser"><code>XMLParser</code></a> skips over processing instructions in the input instead of creating comment objects for them. An <a class="reference internal" href="#xml.etree.ElementTree.ElementTree" title="xml.etree.ElementTree.ElementTree"><code>ElementTree</code></a> will only contain processing instruction nodes if they have been inserted into to the tree using one of the <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code>Element</code></a> methods.</p> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="xml.etree.ElementTree.register_namespace">
+<code>xml.etree.ElementTree.register_namespace(prefix, uri)</code> </dt> <dd>
+<p>Registers a namespace prefix. The registry is global, and any existing mapping for either the given prefix or the namespace URI will be removed. <em>prefix</em> is a namespace prefix. <em>uri</em> is a namespace uri. Tags and attributes in this namespace will be serialized with the given prefix, if at all possible.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="xml.etree.ElementTree.SubElement">
+<code>xml.etree.ElementTree.SubElement(parent, tag, attrib={}, **extra)</code> </dt> <dd>
+<p>Subelement factory. This function creates an element instance, and appends it to an existing element.</p> <p>The element name, attribute names, and attribute values can be either bytestrings or Unicode strings. <em>parent</em> is the parent element. <em>tag</em> is the subelement name. <em>attrib</em> is an optional dictionary, containing element attributes. <em>extra</em> contains additional attributes, given as keyword arguments. Returns an element instance.</p> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="xml.etree.ElementTree.tostring">
+<code>xml.etree.ElementTree.tostring(element, encoding='us-ascii', method='xml', *, xml_declaration=None, default_namespace=None, short_empty_elements=True)</code> </dt> <dd>
+<p>Generates a string representation of an XML element, including all subelements. <em>element</em> is an <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code>Element</code></a> instance. <em>encoding</em> <a class="footnote-reference brackets" href="#id9" id="id1">1</a> is the output encoding (default is US-ASCII). Use <code>encoding="unicode"</code> to generate a Unicode string (otherwise, a bytestring is generated). <em>method</em> is either <code>"xml"</code>, <code>"html"</code> or <code>"text"</code> (default is <code>"xml"</code>). <em>xml_declaration</em>, <em>default_namespace</em> and <em>short_empty_elements</em> has the same meaning as in <a class="reference internal" href="#xml.etree.ElementTree.ElementTree.write" title="xml.etree.ElementTree.ElementTree.write"><code>ElementTree.write()</code></a>. Returns an (optionally) encoded string containing the XML data.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4: </span>The <em>short_empty_elements</em> parameter.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8: </span>The <em>xml_declaration</em> and <em>default_namespace</em> parameters.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>The <a class="reference internal" href="#xml.etree.ElementTree.tostring" title="xml.etree.ElementTree.tostring"><code>tostring()</code></a> function now preserves the attribute order specified by the user.</p> </div> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="xml.etree.ElementTree.tostringlist">
+<code>xml.etree.ElementTree.tostringlist(element, encoding='us-ascii', method='xml', *, xml_declaration=None, default_namespace=None, short_empty_elements=True)</code> </dt> <dd>
+<p>Generates a string representation of an XML element, including all subelements. <em>element</em> is an <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code>Element</code></a> instance. <em>encoding</em> <a class="footnote-reference brackets" href="#id9" id="id2">1</a> is the output encoding (default is US-ASCII). Use <code>encoding="unicode"</code> to generate a Unicode string (otherwise, a bytestring is generated). <em>method</em> is either <code>"xml"</code>, <code>"html"</code> or <code>"text"</code> (default is <code>"xml"</code>). <em>xml_declaration</em>, <em>default_namespace</em> and <em>short_empty_elements</em> has the same meaning as in <a class="reference internal" href="#xml.etree.ElementTree.ElementTree.write" title="xml.etree.ElementTree.ElementTree.write"><code>ElementTree.write()</code></a>. Returns a list of (optionally) encoded strings containing the XML data. It does not guarantee any specific sequence, except that <code>b"".join(tostringlist(element)) == tostring(element)</code>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4: </span>The <em>short_empty_elements</em> parameter.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8: </span>The <em>xml_declaration</em> and <em>default_namespace</em> parameters.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>The <a class="reference internal" href="#xml.etree.ElementTree.tostringlist" title="xml.etree.ElementTree.tostringlist"><code>tostringlist()</code></a> function now preserves the attribute order specified by the user.</p> </div> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="xml.etree.ElementTree.XML">
+<code>xml.etree.ElementTree.XML(text, parser=None)</code> </dt> <dd>
+<p>Parses an XML section from a string constant. This function can be used to embed “XML literals” in Python code. <em>text</em> is a string containing XML data. <em>parser</em> is an optional parser instance. If not given, the standard <a class="reference internal" href="#xml.etree.ElementTree.XMLParser" title="xml.etree.ElementTree.XMLParser"><code>XMLParser</code></a> parser is used. Returns an <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code>Element</code></a> instance.</p> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="xml.etree.ElementTree.XMLID">
+<code>xml.etree.ElementTree.XMLID(text, parser=None)</code> </dt> <dd>
+<p>Parses an XML section from a string constant, and also returns a dictionary which maps from element id:s to elements. <em>text</em> is a string containing XML data. <em>parser</em> is an optional parser instance. If not given, the standard <a class="reference internal" href="#xml.etree.ElementTree.XMLParser" title="xml.etree.ElementTree.XMLParser"><code>XMLParser</code></a> parser is used. Returns a tuple containing an <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code>Element</code></a> instance and a dictionary.</p> </dd>
+</dl> </section> </section> <section id="xinclude-support"> <span id="elementtree-xinclude"></span><h2>XInclude support</h2> <p>This module provides limited support for <a class="reference external" href="https://www.w3.org/TR/xinclude/">XInclude directives</a>, via the <a class="reference internal" href="#module-xml.etree.ElementInclude" title="xml.etree.ElementInclude"><code>xml.etree.ElementInclude</code></a> helper module. This module can be used to insert subtrees and text strings into element trees, based on information in the tree.</p> <section id="id3"> <h3>Example</h3> <p>Here’s an example that demonstrates use of the XInclude module. To include an XML document in the current document, use the <code>{http://www.w3.org/2001/XInclude}include</code> element and set the <strong>parse</strong> attribute to <code>"xml"</code>, and use the <strong>href</strong> attribute to specify the document to include.</p> <pre data-language="xml">&lt;?xml version="1.0"?&gt;
+&lt;document xmlns:xi="http://www.w3.org/2001/XInclude"&gt;
+ &lt;xi:include href="source.xml" parse="xml" /&gt;
+&lt;/document&gt;
+</pre> <p>By default, the <strong>href</strong> attribute is treated as a file name. You can use custom loaders to override this behaviour. Also note that the standard helper does not support XPointer syntax.</p> <p>To process this file, load it as usual, and pass the root element to the <a class="reference internal" href="#module-xml.etree.ElementTree" title="xml.etree.ElementTree: Implementation of the ElementTree API."><code>xml.etree.ElementTree</code></a> module:</p> <pre data-language="python">from xml.etree import ElementTree, ElementInclude
+
+tree = ElementTree.parse("document.xml")
+root = tree.getroot()
+
+ElementInclude.include(root)
+</pre> <p>The ElementInclude module replaces the <code>{http://www.w3.org/2001/XInclude}include</code> element with the root element from the <strong>source.xml</strong> document. The result might look something like this:</p> <pre data-language="xml">&lt;document xmlns:xi="http://www.w3.org/2001/XInclude"&gt;
+ &lt;para&gt;This is a paragraph.&lt;/para&gt;
+&lt;/document&gt;
+</pre> <p>If the <strong>parse</strong> attribute is omitted, it defaults to “xml”. The href attribute is required.</p> <p>To include a text document, use the <code>{http://www.w3.org/2001/XInclude}include</code> element, and set the <strong>parse</strong> attribute to “text”:</p> <pre data-language="xml">&lt;?xml version="1.0"?&gt;
+&lt;document xmlns:xi="http://www.w3.org/2001/XInclude"&gt;
+ Copyright (c) &lt;xi:include href="year.txt" parse="text" /&gt;.
+&lt;/document&gt;
+</pre> <p>The result might look something like:</p> <pre data-language="xml">&lt;document xmlns:xi="http://www.w3.org/2001/XInclude"&gt;
+ Copyright (c) 2003.
+&lt;/document&gt;
+</pre> </section> </section> <section id="id4"> <h2>Reference</h2> <section id="elementinclude-functions"> <span id="id5"></span><h3>Functions</h3> <span class="target" id="module-xml.etree.ElementInclude"></span><dl class="py function"> <dt class="sig sig-object py" id="xml.etree.ElementInclude.default_loader">
+<code>xml.etree.ElementInclude.default_loader(href, parse, encoding=None)</code> </dt> <dd>
+<p>Default loader. This default loader reads an included resource from disk. <em>href</em> is a URL. <em>parse</em> is for parse mode either “xml” or “text”. <em>encoding</em> is an optional text encoding. If not given, encoding is <code>utf-8</code>. Returns the expanded resource. If the parse mode is <code>"xml"</code>, this is an ElementTree instance. If the parse mode is “text”, this is a Unicode string. If the loader fails, it can return None or raise an exception.</p> </dd>
+</dl> <dl class="py function"> <dt class="sig sig-object py" id="xml.etree.ElementInclude.include">
+<code>xml.etree.ElementInclude.include(elem, loader=None, base_url=None, max_depth=6)</code> </dt> <dd>
+<p>This function expands XInclude directives. <em>elem</em> is the root element. <em>loader</em> is an optional resource loader. If omitted, it defaults to <a class="reference internal" href="#xml.etree.ElementInclude.default_loader" title="xml.etree.ElementInclude.default_loader"><code>default_loader()</code></a>. If given, it should be a callable that implements the same interface as <a class="reference internal" href="#xml.etree.ElementInclude.default_loader" title="xml.etree.ElementInclude.default_loader"><code>default_loader()</code></a>. <em>base_url</em> is base URL of the original file, to resolve relative include file references. <em>max_depth</em> is the maximum number of recursive inclusions. Limited to reduce the risk of malicious content explosion. Pass a negative value to disable the limitation.</p> <p>Returns the expanded resource. If the parse mode is <code>"xml"</code>, this is an ElementTree instance. If the parse mode is “text”, this is a Unicode string. If the loader fails, it can return None or raise an exception.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.9: </span>The <em>base_url</em> and <em>max_depth</em> parameters.</p> </div> </dd>
+</dl> </section> <section id="element-objects"> <span id="elementtree-element-objects"></span><h3>Element Objects</h3> <dl class="py class"> <dt class="sig sig-object py" id="xml.etree.ElementTree.Element">
+<code>class xml.etree.ElementTree.Element(tag, attrib={}, **extra)</code> </dt> <dd>
+<p>Element class. This class defines the Element interface, and provides a reference implementation of this interface.</p> <p>The element name, attribute names, and attribute values can be either bytestrings or Unicode strings. <em>tag</em> is the element name. <em>attrib</em> is an optional dictionary, containing element attributes. <em>extra</em> contains additional attributes, given as keyword arguments.</p> <dl class="py attribute"> <dt class="sig sig-object py" id="xml.etree.ElementTree.Element.tag">
+<code>tag</code> </dt> <dd>
+<p>A string identifying what kind of data this element represents (the element type, in other words).</p> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="xml.etree.ElementTree.Element.text">
+<code>text</code> </dt> <dt class="sig sig-object py" id="xml.etree.ElementTree.Element.tail">
+<code>tail</code> </dt> <dd>
+<p>These attributes can be used to hold additional data associated with the element. Their values are usually strings but may be any application-specific object. If the element is created from an XML file, the <em>text</em> attribute holds either the text between the element’s start tag and its first child or end tag, or <code>None</code>, and the <em>tail</em> attribute holds either the text between the element’s end tag and the next tag, or <code>None</code>. For the XML data</p> <pre data-language="xml">&lt;a&gt;&lt;b&gt;1&lt;c&gt;2&lt;d/&gt;3&lt;/c&gt;&lt;/b&gt;4&lt;/a&gt;
+</pre> <p>the <em>a</em> element has <code>None</code> for both <em>text</em> and <em>tail</em> attributes, the <em>b</em> element has <em>text</em> <code>"1"</code> and <em>tail</em> <code>"4"</code>, the <em>c</em> element has <em>text</em> <code>"2"</code> and <em>tail</em> <code>None</code>, and the <em>d</em> element has <em>text</em> <code>None</code> and <em>tail</em> <code>"3"</code>.</p> <p>To collect the inner text of an element, see <a class="reference internal" href="#xml.etree.ElementTree.Element.itertext" title="xml.etree.ElementTree.Element.itertext"><code>itertext()</code></a>, for example <code>"".join(element.itertext())</code>.</p> <p>Applications may store arbitrary objects in these attributes.</p> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="xml.etree.ElementTree.Element.attrib">
+<code>attrib</code> </dt> <dd>
+<p>A dictionary containing the element’s attributes. Note that while the <em>attrib</em> value is always a real mutable Python dictionary, an ElementTree implementation may choose to use another internal representation, and create the dictionary only if someone asks for it. To take advantage of such implementations, use the dictionary methods below whenever possible.</p> </dd>
+</dl> <p>The following dictionary-like methods work on the element attributes.</p> <dl class="py method"> <dt class="sig sig-object py" id="xml.etree.ElementTree.Element.clear">
+<code>clear()</code> </dt> <dd>
+<p>Resets an element. This function removes all subelements, clears all attributes, and sets the text and tail attributes to <code>None</code>.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="xml.etree.ElementTree.Element.get">
+<code>get(key, default=None)</code> </dt> <dd>
+<p>Gets the element attribute named <em>key</em>.</p> <p>Returns the attribute value, or <em>default</em> if the attribute was not found.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="xml.etree.ElementTree.Element.items">
+<code>items()</code> </dt> <dd>
+<p>Returns the element attributes as a sequence of (name, value) pairs. The attributes are returned in an arbitrary order.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="xml.etree.ElementTree.Element.keys">
+<code>keys()</code> </dt> <dd>
+<p>Returns the elements attribute names as a list. The names are returned in an arbitrary order.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="xml.etree.ElementTree.Element.set">
+<code>set(key, value)</code> </dt> <dd>
+<p>Set the attribute <em>key</em> on the element to <em>value</em>.</p> </dd>
+</dl> <p>The following methods work on the element’s children (subelements).</p> <dl class="py method"> <dt class="sig sig-object py" id="xml.etree.ElementTree.Element.append">
+<code>append(subelement)</code> </dt> <dd>
+<p>Adds the element <em>subelement</em> to the end of this element’s internal list of subelements. Raises <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a> if <em>subelement</em> is not an <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code>Element</code></a>.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="xml.etree.ElementTree.Element.extend">
+<code>extend(subelements)</code> </dt> <dd>
+<p>Appends <em>subelements</em> from a sequence object with zero or more elements. Raises <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a> if a subelement is not an <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code>Element</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="xml.etree.ElementTree.Element.find">
+<code>find(match, namespaces=None)</code> </dt> <dd>
+<p>Finds the first subelement matching <em>match</em>. <em>match</em> may be a tag name or a <a class="reference internal" href="#elementtree-xpath"><span class="std std-ref">path</span></a>. Returns an element instance or <code>None</code>. <em>namespaces</em> is an optional mapping from namespace prefix to full name. Pass <code>''</code> as prefix to move all unprefixed tag names in the expression into the given namespace.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="xml.etree.ElementTree.Element.findall">
+<code>findall(match, namespaces=None)</code> </dt> <dd>
+<p>Finds all matching subelements, by tag name or <a class="reference internal" href="#elementtree-xpath"><span class="std std-ref">path</span></a>. Returns a list containing all matching elements in document order. <em>namespaces</em> is an optional mapping from namespace prefix to full name. Pass <code>''</code> as prefix to move all unprefixed tag names in the expression into the given namespace.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="xml.etree.ElementTree.Element.findtext">
+<code>findtext(match, default=None, namespaces=None)</code> </dt> <dd>
+<p>Finds text for the first subelement matching <em>match</em>. <em>match</em> may be a tag name or a <a class="reference internal" href="#elementtree-xpath"><span class="std std-ref">path</span></a>. Returns the text content of the first matching element, or <em>default</em> if no element was found. Note that if the matching element has no text content an empty string is returned. <em>namespaces</em> is an optional mapping from namespace prefix to full name. Pass <code>''</code> as prefix to move all unprefixed tag names in the expression into the given namespace.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="xml.etree.ElementTree.Element.insert">
+<code>insert(index, subelement)</code> </dt> <dd>
+<p>Inserts <em>subelement</em> at the given position in this element. Raises <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a> if <em>subelement</em> is not an <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code>Element</code></a>.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="xml.etree.ElementTree.Element.iter">
+<code>iter(tag=None)</code> </dt> <dd>
+<p>Creates a tree <a class="reference internal" href="../glossary#term-iterator"><span class="xref std std-term">iterator</span></a> with the current element as the root. The iterator iterates over this element and all elements below it, in document (depth first) order. If <em>tag</em> is not <code>None</code> or <code>'*'</code>, only elements whose tag equals <em>tag</em> are returned from the iterator. If the tree structure is modified during iteration, the result is undefined.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="xml.etree.ElementTree.Element.iterfind">
+<code>iterfind(match, namespaces=None)</code> </dt> <dd>
+<p>Finds all matching subelements, by tag name or <a class="reference internal" href="#elementtree-xpath"><span class="std std-ref">path</span></a>. Returns an iterable yielding all matching elements in document order. <em>namespaces</em> is an optional mapping from namespace prefix to full name.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="xml.etree.ElementTree.Element.itertext">
+<code>itertext()</code> </dt> <dd>
+<p>Creates a text iterator. The iterator loops over this element and all subelements, in document order, and returns all inner text.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="xml.etree.ElementTree.Element.makeelement">
+<code>makeelement(tag, attrib)</code> </dt> <dd>
+<p>Creates a new element object of the same type as this element. Do not call this method, use the <a class="reference internal" href="#xml.etree.ElementTree.SubElement" title="xml.etree.ElementTree.SubElement"><code>SubElement()</code></a> factory function instead.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="xml.etree.ElementTree.Element.remove">
+<code>remove(subelement)</code> </dt> <dd>
+<p>Removes <em>subelement</em> from the element. Unlike the find* methods this method compares elements based on the instance identity, not on tag value or contents.</p> </dd>
+</dl> <p><a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code>Element</code></a> objects also support the following sequence type methods for working with subelements: <a class="reference internal" href="../reference/datamodel#object.__delitem__" title="object.__delitem__"><code>__delitem__()</code></a>, <a class="reference internal" href="../reference/datamodel#object.__getitem__" title="object.__getitem__"><code>__getitem__()</code></a>, <a class="reference internal" href="../reference/datamodel#object.__setitem__" title="object.__setitem__"><code>__setitem__()</code></a>, <a class="reference internal" href="../reference/datamodel#object.__len__" title="object.__len__"><code>__len__()</code></a>.</p> <p>Caution: Elements with no subelements will test as <code>False</code>. Testing the truth value of an Element is deprecated and will raise an exception in Python 3.14. Use specific <code>len(elem)</code> or <code>elem is None</code> test instead.:</p> <pre data-language="python">element = root.find('foo')
+
+if not element: # careful!
+ print("element not found, or element has no subelements")
+
+if element is None:
+ print("element not found")
+</pre> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>Testing the truth value of an Element emits <a class="reference internal" href="exceptions#DeprecationWarning" title="DeprecationWarning"><code>DeprecationWarning</code></a>.</p> </div> <p>Prior to Python 3.8, the serialisation order of the XML attributes of elements was artificially made predictable by sorting the attributes by their name. Based on the now guaranteed ordering of dicts, this arbitrary reordering was removed in Python 3.8 to preserve the order in which attributes were originally parsed or created by user code.</p> <p>In general, user code should try not to depend on a specific ordering of attributes, given that the <a class="reference external" href="https://www.w3.org/TR/xml-infoset/">XML Information Set</a> explicitly excludes the attribute order from conveying information. Code should be prepared to deal with any ordering on input. In cases where deterministic XML output is required, e.g. for cryptographic signing or test data sets, canonical serialisation is available with the <a class="reference internal" href="#xml.etree.ElementTree.canonicalize" title="xml.etree.ElementTree.canonicalize"><code>canonicalize()</code></a> function.</p> <p>In cases where canonical output is not applicable but a specific attribute order is still desirable on output, code should aim for creating the attributes directly in the desired order, to avoid perceptual mismatches for readers of the code. In cases where this is difficult to achieve, a recipe like the following can be applied prior to serialisation to enforce an order independently from the Element creation:</p> <pre data-language="python">def reorder_attributes(root):
+ for el in root.iter():
+ attrib = el.attrib
+ if len(attrib) &gt; 1:
+ # adjust attribute order, e.g. by sorting
+ attribs = sorted(attrib.items())
+ attrib.clear()
+ attrib.update(attribs)
+</pre> </dd>
+</dl> </section> <section id="elementtree-objects"> <span id="elementtree-elementtree-objects"></span><h3>ElementTree Objects</h3> <dl class="py class"> <dt class="sig sig-object py" id="xml.etree.ElementTree.ElementTree">
+<code>class xml.etree.ElementTree.ElementTree(element=None, file=None)</code> </dt> <dd>
+<p>ElementTree wrapper class. This class represents an entire element hierarchy, and adds some extra support for serialization to and from standard XML.</p> <p><em>element</em> is the root element. The tree is initialized with the contents of the XML <em>file</em> if given.</p> <dl class="py method"> <dt class="sig sig-object py" id="xml.etree.ElementTree.ElementTree._setroot">
+<code>_setroot(element)</code> </dt> <dd>
+<p>Replaces the root element for this tree. This discards the current contents of the tree, and replaces it with the given element. Use with care. <em>element</em> is an element instance.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="xml.etree.ElementTree.ElementTree.find">
+<code>find(match, namespaces=None)</code> </dt> <dd>
+<p>Same as <a class="reference internal" href="#xml.etree.ElementTree.Element.find" title="xml.etree.ElementTree.Element.find"><code>Element.find()</code></a>, starting at the root of the tree.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="xml.etree.ElementTree.ElementTree.findall">
+<code>findall(match, namespaces=None)</code> </dt> <dd>
+<p>Same as <a class="reference internal" href="#xml.etree.ElementTree.Element.findall" title="xml.etree.ElementTree.Element.findall"><code>Element.findall()</code></a>, starting at the root of the tree.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="xml.etree.ElementTree.ElementTree.findtext">
+<code>findtext(match, default=None, namespaces=None)</code> </dt> <dd>
+<p>Same as <a class="reference internal" href="#xml.etree.ElementTree.Element.findtext" title="xml.etree.ElementTree.Element.findtext"><code>Element.findtext()</code></a>, starting at the root of the tree.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="xml.etree.ElementTree.ElementTree.getroot">
+<code>getroot()</code> </dt> <dd>
+<p>Returns the root element for this tree.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="xml.etree.ElementTree.ElementTree.iter">
+<code>iter(tag=None)</code> </dt> <dd>
+<p>Creates and returns a tree iterator for the root element. The iterator loops over all elements in this tree, in section order. <em>tag</em> is the tag to look for (default is to return all elements).</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="xml.etree.ElementTree.ElementTree.iterfind">
+<code>iterfind(match, namespaces=None)</code> </dt> <dd>
+<p>Same as <a class="reference internal" href="#xml.etree.ElementTree.Element.iterfind" title="xml.etree.ElementTree.Element.iterfind"><code>Element.iterfind()</code></a>, starting at the root of the tree.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="xml.etree.ElementTree.ElementTree.parse">
+<code>parse(source, parser=None)</code> </dt> <dd>
+<p>Loads an external XML section into this element tree. <em>source</em> is a file name or <a class="reference internal" href="../glossary#term-file-object"><span class="xref std std-term">file object</span></a>. <em>parser</em> is an optional parser instance. If not given, the standard <a class="reference internal" href="#xml.etree.ElementTree.XMLParser" title="xml.etree.ElementTree.XMLParser"><code>XMLParser</code></a> parser is used. Returns the section root element.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="xml.etree.ElementTree.ElementTree.write">
+<code>write(file, encoding='us-ascii', xml_declaration=None, default_namespace=None, method='xml', *, short_empty_elements=True)</code> </dt> <dd>
+<p>Writes the element tree to a file, as XML. <em>file</em> is a file name, or a <a class="reference internal" href="../glossary#term-file-object"><span class="xref std std-term">file object</span></a> opened for writing. <em>encoding</em> <a class="footnote-reference brackets" href="#id9" id="id6">1</a> is the output encoding (default is US-ASCII). <em>xml_declaration</em> controls if an XML declaration should be added to the file. Use <code>False</code> for never, <code>True</code> for always, <code>None</code> for only if not US-ASCII or UTF-8 or Unicode (default is <code>None</code>). <em>default_namespace</em> sets the default XML namespace (for “xmlns”). <em>method</em> is either <code>"xml"</code>, <code>"html"</code> or <code>"text"</code> (default is <code>"xml"</code>). The keyword-only <em>short_empty_elements</em> parameter controls the formatting of elements that contain no content. If <code>True</code> (the default), they are emitted as a single self-closed tag, otherwise they are emitted as a pair of start/end tags.</p> <p>The output is either a string (<a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a>) or binary (<a class="reference internal" href="stdtypes#bytes" title="bytes"><code>bytes</code></a>). This is controlled by the <em>encoding</em> argument. If <em>encoding</em> is <code>"unicode"</code>, the output is a string; otherwise, it’s binary. Note that this may conflict with the type of <em>file</em> if it’s an open <a class="reference internal" href="../glossary#term-file-object"><span class="xref std std-term">file object</span></a>; make sure you do not try to write a string to a binary stream and vice versa.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4: </span>The <em>short_empty_elements</em> parameter.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>The <a class="reference internal" href="#xml.etree.ElementTree.ElementTree.write" title="xml.etree.ElementTree.ElementTree.write"><code>write()</code></a> method now preserves the attribute order specified by the user.</p> </div> </dd>
+</dl> </dd>
+</dl> <p>This is the XML file that is going to be manipulated:</p> <pre data-language="python">&lt;html&gt;
+ &lt;head&gt;
+ &lt;title&gt;Example page&lt;/title&gt;
+ &lt;/head&gt;
+ &lt;body&gt;
+ &lt;p&gt;Moved to &lt;a href="http://example.org/"&gt;example.org&lt;/a&gt;
+ or &lt;a href="http://example.com/"&gt;example.com&lt;/a&gt;.&lt;/p&gt;
+ &lt;/body&gt;
+&lt;/html&gt;
+</pre> <p>Example of changing the attribute “target” of every link in first paragraph:</p> <pre data-language="python">&gt;&gt;&gt; from xml.etree.ElementTree import ElementTree
+&gt;&gt;&gt; tree = ElementTree()
+&gt;&gt;&gt; tree.parse("index.xhtml")
+&lt;Element 'html' at 0xb77e6fac&gt;
+&gt;&gt;&gt; p = tree.find("body/p") # Finds first occurrence of tag p in body
+&gt;&gt;&gt; p
+&lt;Element 'p' at 0xb77ec26c&gt;
+&gt;&gt;&gt; links = list(p.iter("a")) # Returns list of all links
+&gt;&gt;&gt; links
+[&lt;Element 'a' at 0xb77ec2ac&gt;, &lt;Element 'a' at 0xb77ec1cc&gt;]
+&gt;&gt;&gt; for i in links: # Iterates through all found links
+... i.attrib["target"] = "blank"
+...
+&gt;&gt;&gt; tree.write("output.xhtml")
+</pre> </section> <section id="qname-objects"> <span id="elementtree-qname-objects"></span><h3>QName Objects</h3> <dl class="py class"> <dt class="sig sig-object py" id="xml.etree.ElementTree.QName">
+<code>class xml.etree.ElementTree.QName(text_or_uri, tag=None)</code> </dt> <dd>
+<p>QName wrapper. This can be used to wrap a QName attribute value, in order to get proper namespace handling on output. <em>text_or_uri</em> is a string containing the QName value, in the form {uri}local, or, if the tag argument is given, the URI part of a QName. If <em>tag</em> is given, the first argument is interpreted as a URI, and this argument is interpreted as a local name. <a class="reference internal" href="#xml.etree.ElementTree.QName" title="xml.etree.ElementTree.QName"><code>QName</code></a> instances are opaque.</p> </dd>
+</dl> </section> <section id="treebuilder-objects"> <span id="elementtree-treebuilder-objects"></span><h3>TreeBuilder Objects</h3> <dl class="py class"> <dt class="sig sig-object py" id="xml.etree.ElementTree.TreeBuilder">
+<code>class xml.etree.ElementTree.TreeBuilder(element_factory=None, *, comment_factory=None, pi_factory=None, insert_comments=False, insert_pis=False)</code> </dt> <dd>
+<p>Generic element structure builder. This builder converts a sequence of start, data, end, comment and pi method calls to a well-formed element structure. You can use this class to build an element structure using a custom XML parser, or a parser for some other XML-like format.</p> <p><em>element_factory</em>, when given, must be a callable accepting two positional arguments: a tag and a dict of attributes. It is expected to return a new element instance.</p> <p>The <em>comment_factory</em> and <em>pi_factory</em> functions, when given, should behave like the <a class="reference internal" href="#xml.etree.ElementTree.Comment" title="xml.etree.ElementTree.Comment"><code>Comment()</code></a> and <a class="reference internal" href="#xml.etree.ElementTree.ProcessingInstruction" title="xml.etree.ElementTree.ProcessingInstruction"><code>ProcessingInstruction()</code></a> functions to create comments and processing instructions. When not given, the default factories will be used. When <em>insert_comments</em> and/or <em>insert_pis</em> is true, comments/pis will be inserted into the tree if they appear within the root element (but not outside of it).</p> <dl class="py method"> <dt class="sig sig-object py" id="xml.etree.ElementTree.TreeBuilder.close">
+<code>close()</code> </dt> <dd>
+<p>Flushes the builder buffers, and returns the toplevel document element. Returns an <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code>Element</code></a> instance.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="xml.etree.ElementTree.TreeBuilder.data">
+<code>data(data)</code> </dt> <dd>
+<p>Adds text to the current element. <em>data</em> is a string. This should be either a bytestring, or a Unicode string.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="xml.etree.ElementTree.TreeBuilder.end">
+<code>end(tag)</code> </dt> <dd>
+<p>Closes the current element. <em>tag</em> is the element name. Returns the closed element.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="xml.etree.ElementTree.TreeBuilder.start">
+<code>start(tag, attrs)</code> </dt> <dd>
+<p>Opens a new element. <em>tag</em> is the element name. <em>attrs</em> is a dictionary containing element attributes. Returns the opened element.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="xml.etree.ElementTree.TreeBuilder.comment">
+<code>comment(text)</code> </dt> <dd>
+<p>Creates a comment with the given <em>text</em>. If <code>insert_comments</code> is true, this will also add it to the tree.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="xml.etree.ElementTree.TreeBuilder.pi">
+<code>pi(target, text)</code> </dt> <dd>
+<p>Creates a comment with the given <em>target</em> name and <em>text</em>. If <code>insert_pis</code> is true, this will also add it to the tree.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> </dd>
+</dl> <p>In addition, a custom <a class="reference internal" href="#xml.etree.ElementTree.TreeBuilder" title="xml.etree.ElementTree.TreeBuilder"><code>TreeBuilder</code></a> object can provide the following methods:</p> <dl class="py method"> <dt class="sig sig-object py" id="xml.etree.ElementTree.TreeBuilder.doctype">
+<code>doctype(name, pubid, system)</code> </dt> <dd>
+<p>Handles a doctype declaration. <em>name</em> is the doctype name. <em>pubid</em> is the public identifier. <em>system</em> is the system identifier. This method does not exist on the default <a class="reference internal" href="#xml.etree.ElementTree.TreeBuilder" title="xml.etree.ElementTree.TreeBuilder"><code>TreeBuilder</code></a> class.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="xml.etree.ElementTree.TreeBuilder.start_ns">
+<code>start_ns(prefix, uri)</code> </dt> <dd>
+<p>Is called whenever the parser encounters a new namespace declaration, before the <code>start()</code> callback for the opening element that defines it. <em>prefix</em> is <code>''</code> for the default namespace and the declared namespace prefix name otherwise. <em>uri</em> is the namespace URI.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="xml.etree.ElementTree.TreeBuilder.end_ns">
+<code>end_ns(prefix)</code> </dt> <dd>
+<p>Is called after the <code>end()</code> callback of an element that declared a namespace prefix mapping, with the name of the <em>prefix</em> that went out of scope.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> </dd>
+</dl> </dd>
+</dl> <dl class="py class"> <dt class="sig sig-object py" id="xml.etree.ElementTree.C14NWriterTarget">
+<code>class xml.etree.ElementTree.C14NWriterTarget(write, *, with_comments=False, strip_text=False, rewrite_prefixes=False, qname_aware_tags=None, qname_aware_attrs=None, exclude_attrs=None, exclude_tags=None)</code> </dt> <dd>
+<p>A <a class="reference external" href="https://www.w3.org/TR/xml-c14n2/">C14N 2.0</a> writer. Arguments are the same as for the <a class="reference internal" href="#xml.etree.ElementTree.canonicalize" title="xml.etree.ElementTree.canonicalize"><code>canonicalize()</code></a> function. This class does not build a tree but translates the callback events directly into a serialised form using the <em>write</em> function.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.8.</span></p> </div> </dd>
+</dl> </section> <section id="xmlparser-objects"> <span id="elementtree-xmlparser-objects"></span><h3>XMLParser Objects</h3> <dl class="py class"> <dt class="sig sig-object py" id="xml.etree.ElementTree.XMLParser">
+<code>class xml.etree.ElementTree.XMLParser(*, target=None, encoding=None)</code> </dt> <dd>
+<p>This class is the low-level building block of the module. It uses <a class="reference internal" href="pyexpat#module-xml.parsers.expat" title="xml.parsers.expat: An interface to the Expat non-validating XML parser."><code>xml.parsers.expat</code></a> for efficient, event-based parsing of XML. It can be fed XML data incrementally with the <a class="reference internal" href="#xml.etree.ElementTree.XMLParser.feed" title="xml.etree.ElementTree.XMLParser.feed"><code>feed()</code></a> method, and parsing events are translated to a push API - by invoking callbacks on the <em>target</em> object. If <em>target</em> is omitted, the standard <a class="reference internal" href="#xml.etree.ElementTree.TreeBuilder" title="xml.etree.ElementTree.TreeBuilder"><code>TreeBuilder</code></a> is used. If <em>encoding</em> <a class="footnote-reference brackets" href="#id9" id="id8">1</a> is given, the value overrides the encoding specified in the XML file.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>Parameters are now <a class="reference internal" href="../glossary#keyword-only-parameter"><span class="std std-ref">keyword-only</span></a>. The <em>html</em> argument no longer supported.</p> </div> <dl class="py method"> <dt class="sig sig-object py" id="xml.etree.ElementTree.XMLParser.close">
+<code>close()</code> </dt> <dd>
+<p>Finishes feeding data to the parser. Returns the result of calling the <code>close()</code> method of the <em>target</em> passed during construction; by default, this is the toplevel document element.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="xml.etree.ElementTree.XMLParser.feed">
+<code>feed(data)</code> </dt> <dd>
+<p>Feeds data to the parser. <em>data</em> is encoded data.</p> </dd>
+</dl> <p><a class="reference internal" href="#xml.etree.ElementTree.XMLParser.feed" title="xml.etree.ElementTree.XMLParser.feed"><code>XMLParser.feed()</code></a> calls <em>target</em>'s <code>start(tag, attrs_dict)</code> method for each opening tag, its <code>end(tag)</code> method for each closing tag, and data is processed by method <code>data(data)</code>. For further supported callback methods, see the <a class="reference internal" href="#xml.etree.ElementTree.TreeBuilder" title="xml.etree.ElementTree.TreeBuilder"><code>TreeBuilder</code></a> class. <a class="reference internal" href="#xml.etree.ElementTree.XMLParser.close" title="xml.etree.ElementTree.XMLParser.close"><code>XMLParser.close()</code></a> calls <em>target</em>'s method <code>close()</code>. <a class="reference internal" href="#xml.etree.ElementTree.XMLParser" title="xml.etree.ElementTree.XMLParser"><code>XMLParser</code></a> can be used not only for building a tree structure. This is an example of counting the maximum depth of an XML file:</p> <pre data-language="python">&gt;&gt;&gt; from xml.etree.ElementTree import XMLParser
+&gt;&gt;&gt; class MaxDepth: # The target object of the parser
+... maxDepth = 0
+... depth = 0
+... def start(self, tag, attrib): # Called for each opening tag.
+... self.depth += 1
+... if self.depth &gt; self.maxDepth:
+... self.maxDepth = self.depth
+... def end(self, tag): # Called for each closing tag.
+... self.depth -= 1
+... def data(self, data):
+... pass # We do not need to do anything with data.
+... def close(self): # Called when all data has been parsed.
+... return self.maxDepth
+...
+&gt;&gt;&gt; target = MaxDepth()
+&gt;&gt;&gt; parser = XMLParser(target=target)
+&gt;&gt;&gt; exampleXml = """
+... &lt;a&gt;
+... &lt;b&gt;
+... &lt;/b&gt;
+... &lt;b&gt;
+... &lt;c&gt;
+... &lt;d&gt;
+... &lt;/d&gt;
+... &lt;/c&gt;
+... &lt;/b&gt;
+... &lt;/a&gt;"""
+&gt;&gt;&gt; parser.feed(exampleXml)
+&gt;&gt;&gt; parser.close()
+4
+</pre> </dd>
+</dl> </section> <section id="xmlpullparser-objects"> <span id="elementtree-xmlpullparser-objects"></span><h3>XMLPullParser Objects</h3> <dl class="py class"> <dt class="sig sig-object py" id="xml.etree.ElementTree.XMLPullParser">
+<code>class xml.etree.ElementTree.XMLPullParser(events=None)</code> </dt> <dd>
+<p>A pull parser suitable for non-blocking applications. Its input-side API is similar to that of <a class="reference internal" href="#xml.etree.ElementTree.XMLParser" title="xml.etree.ElementTree.XMLParser"><code>XMLParser</code></a>, but instead of pushing calls to a callback target, <a class="reference internal" href="#xml.etree.ElementTree.XMLPullParser" title="xml.etree.ElementTree.XMLPullParser"><code>XMLPullParser</code></a> collects an internal list of parsing events and lets the user read from it. <em>events</em> is a sequence of events to report back. The supported events are the strings <code>"start"</code>, <code>"end"</code>, <code>"comment"</code>, <code>"pi"</code>, <code>"start-ns"</code> and <code>"end-ns"</code> (the “ns” events are used to get detailed namespace information). If <em>events</em> is omitted, only <code>"end"</code> events are reported.</p> <dl class="py method"> <dt class="sig sig-object py" id="xml.etree.ElementTree.XMLPullParser.feed">
+<code>feed(data)</code> </dt> <dd>
+<p>Feed the given bytes data to the parser.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="xml.etree.ElementTree.XMLPullParser.close">
+<code>close()</code> </dt> <dd>
+<p>Signal the parser that the data stream is terminated. Unlike <a class="reference internal" href="#xml.etree.ElementTree.XMLParser.close" title="xml.etree.ElementTree.XMLParser.close"><code>XMLParser.close()</code></a>, this method always returns <a class="reference internal" href="constants#None" title="None"><code>None</code></a>. Any events not yet retrieved when the parser is closed can still be read with <a class="reference internal" href="#xml.etree.ElementTree.XMLPullParser.read_events" title="xml.etree.ElementTree.XMLPullParser.read_events"><code>read_events()</code></a>.</p> </dd>
+</dl> <dl class="py method"> <dt class="sig sig-object py" id="xml.etree.ElementTree.XMLPullParser.read_events">
+<code>read_events()</code> </dt> <dd>
+<p>Return an iterator over the events which have been encountered in the data fed to the parser. The iterator yields <code>(event, elem)</code> pairs, where <em>event</em> is a string representing the type of event (e.g. <code>"end"</code>) and <em>elem</em> is the encountered <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code>Element</code></a> object, or other context value as follows.</p> <ul class="simple"> <li>
+<code>start</code>, <code>end</code>: the current Element.</li> <li>
+<code>comment</code>, <code>pi</code>: the current comment / processing instruction</li> <li>
+<code>start-ns</code>: a tuple <code>(prefix, uri)</code> naming the declared namespace mapping.</li> <li>
+<code>end-ns</code>: <a class="reference internal" href="constants#None" title="None"><code>None</code></a> (this may change in a future version)</li> </ul> <p>Events provided in a previous call to <a class="reference internal" href="#xml.etree.ElementTree.XMLPullParser.read_events" title="xml.etree.ElementTree.XMLPullParser.read_events"><code>read_events()</code></a> will not be yielded again. Events are consumed from the internal queue only when they are retrieved from the iterator, so multiple readers iterating in parallel over iterators obtained from <a class="reference internal" href="#xml.etree.ElementTree.XMLPullParser.read_events" title="xml.etree.ElementTree.XMLPullParser.read_events"><code>read_events()</code></a> will have unpredictable results.</p> </dd>
+</dl> <div class="admonition note"> <p class="admonition-title">Note</p> <p><a class="reference internal" href="#xml.etree.ElementTree.XMLPullParser" title="xml.etree.ElementTree.XMLPullParser"><code>XMLPullParser</code></a> only guarantees that it has seen the “&gt;” character of a starting tag when it emits a “start” event, so the attributes are defined, but the contents of the text and tail attributes are undefined at that point. The same applies to the element children; they may or may not be present.</p> <p>If you need a fully populated element, look for “end” events instead.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>The <code>comment</code> and <code>pi</code> events were added.</p> </div> </dd>
+</dl> </section> <section id="exceptions"> <h3>Exceptions</h3> <dl class="py class"> <dt class="sig sig-object py" id="xml.etree.ElementTree.ParseError">
+<code>class xml.etree.ElementTree.ParseError</code> </dt> <dd>
+<p>XML parse error, raised by the various parsing methods in this module when parsing fails. The string representation of an instance of this exception will contain a user-friendly error message. In addition, it will have the following attributes available:</p> <dl class="py attribute"> <dt class="sig sig-object py" id="xml.etree.ElementTree.ParseError.code">
+<code>code</code> </dt> <dd>
+<p>A numeric error code from the expat parser. See the documentation of <a class="reference internal" href="pyexpat#module-xml.parsers.expat" title="xml.parsers.expat: An interface to the Expat non-validating XML parser."><code>xml.parsers.expat</code></a> for the list of error codes and their meanings.</p> </dd>
+</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="xml.etree.ElementTree.ParseError.position">
+<code>position</code> </dt> <dd>
+<p>A tuple of <em>line</em>, <em>column</em> numbers, specifying where the error occurred.</p> </dd>
+</dl> </dd>
+</dl> <h4 class="rubric">Footnotes</h4> <dl class="footnote brackets"> <dt class="label" id="id9">
+<code>1(1,2,3,4)</code> </dt> <dd>
+<p>The encoding string included in XML output should conform to the appropriate standards. For example, “UTF-8” is valid, but “UTF8” is not. See <a class="reference external" href="https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl">https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl</a> and <a class="reference external" href="https://www.iana.org/assignments/character-sets/character-sets.xhtml">https://www.iana.org/assignments/character-sets/character-sets.xhtml</a>.</p> </dd> </dl> </section> </section> <div class="_attribution">
+ <p class="_attribution-p">
+ &copy; 2001&ndash;2023 Python Software Foundation<br>Licensed under the PSF License.<br>
+ <a href="https://docs.python.org/3.12/library/xml.etree.elementtree.html" class="_attribution-link">https://docs.python.org/3.12/library/xml.etree.elementtree.html</a>
+ </p>
+</div>