xml.etree.ElementTree
— The ElementTree XML API¶
Source code:Lib/xml/etree/ElementTree.py
Thexml.etree.ElementTree
module implements a simple and efficient APIfor parsing and creating XML data.
Changed in version 3.3:This module will use a fast implementation whenever available.
Deprecated since version 3.3:Thexml.etree.cElementTree
module is deprecated.
Warning
Thexml.etree.ElementTree
module is not secure againstmaliciously constructed data. If you need to parse untrusted orunauthenticated data seeXML vulnerabilities.
Tutorial¶
This is a short tutorial for usingxml.etree.ElementTree
(ET
inshort). The goal is to demonstrate some of the building blocks and basicconcepts of the module.
XML tree and elements¶
XML is an inherently hierarchical data format, and the most natural way torepresent it is with a tree.ET
has two classes for this purpose -ElementTree
represents the whole XML document as a tree, andElement
represents a single node in this tree. Interactions withthe whole document (reading and writing to/from files) are usually doneon theElementTree
level. Interactions with a single XML elementand its sub-elements are done on theElement
level.
Parsing XML¶
We’ll be using the fictivecountry_data.xml
XML document as the sample data for this section:
<?xml version="1.0"?><data><countryname="Liechtenstein"><rank>1</rank><year>2008</year><gdppc>141100</gdppc><neighborname="Austria"direction="E"/><neighborname="Switzerland"direction="W"/></country><countryname="Singapore"><rank>4</rank><year>2011</year><gdppc>59900</gdppc><neighborname="Malaysia"direction="N"/></country><countryname="Panama"><rank>68</rank><year>2011</year><gdppc>13600</gdppc><neighborname="Costa Rica"direction="W"/><neighborname="Colombia"direction="E"/></country></data>
We can import this data by reading from a file:
importxml.etree.ElementTreeasETtree=ET.parse('country_data.xml')root=tree.getroot()
Or directly from a string:
root=ET.fromstring(country_data_as_string)
fromstring()
parses XML from a string directly into anElement
,which is the root element of the parsed tree. Other parsing functions maycreate anElementTree
. Check the documentation to be sure.
As anElement
,root
has a tag and a dictionary of attributes:
>>>root.tag'data'>>>root.attrib{}
It also has children nodes over which we can iterate:
>>>forchildinroot:...print(child.tag,child.attrib)...country {'name': 'Liechtenstein'}country {'name': 'Singapore'}country {'name': 'Panama'}
Children are nested, and we can access specific child nodes by index:
>>>root[0][1].text'2008'
Note
Not all elements of the XML input will end up as elements of theparsed tree. Currently, this module skips over any XML comments,processing instructions, and document type declarations in theinput. Nevertheless, trees built using this module’s API ratherthan parsing from XML text can have comments and processinginstructions in them; they will be included when generating XMLoutput. A document type declaration may be accessed by passing acustomTreeBuilder
instance to theXMLParser
constructor.
Pull API for non-blocking parsing¶
Most parsing functions provided by this module require the whole documentto be read at once before returning any result. It is possible to use anXMLParser
and feed data into it incrementally, but it is a push API thatcalls methods on a callback target, which is too low-level and inconvenient formost needs. Sometimes what the user really wants is to be able to parse XMLincrementally, without blocking operations, while enjoying the convenience offully constructedElement
objects.
The most powerful tool for doing this isXMLPullParser
. It does notrequire a blocking read to obtain the XML data, and is instead fed with dataincrementally withXMLPullParser.feed()
calls. To get the parsed XMLelements, callXMLPullParser.read_events()
. Here is an example:
>>>parser=ET.XMLPullParser(['start','end'])>>>parser.feed('<mytag>sometext')>>>list(parser.read_events())[('start', <Element 'mytag' at 0x7fa66db2be58>)]>>>parser.feed(' more text</mytag>')>>>forevent,eleminparser.read_events():...print(event)...print(elem.tag,'text=',elem.text)...endmytag text= sometext more text
The obvious use case is applications that operate in a non-blocking fashionwhere the XML data is being received from a socket or read incrementally fromsome storage device. In such cases, blocking reads are unacceptable.
Because it’s so flexible,XMLPullParser
can be inconvenient to use forsimpler use-cases. If you don’t mind your application blocking on reading XMLdata but would still like to have incremental parsing capabilities, take a lookatiterparse()
. It can be useful when you’re reading a large XML documentand don’t want to hold it wholly in memory.
Whereimmediate feedback through events is wanted, calling methodXMLPullParser.flush()
can help reduce delay;please make sure to study the related security notes.
Finding interesting elements¶
Element
has some useful methods that help iterate recursively over allthe sub-tree below it (its children, their children, and so on). For example,Element.iter()
:
>>>forneighborinroot.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'}
Element.findall()
finds only elements with a tag which are directchildren of the current element.Element.find()
finds thefirst childwith a particular tag, andElement.text
accesses the element’s textcontent.Element.get()
accesses the element’s attributes:
>>>forcountryinroot.findall('country'):...rank=country.find('rank').text...name=country.get('name')...print(name,rank)...Liechtenstein 1Singapore 4Panama 68
More sophisticated specification of which elements to look for is possible byusingXPath.
Modifying an XML File¶
ElementTree
provides a simple way to build XML documents and write them to files.TheElementTree.write()
method serves this purpose.
Once created, anElement
object may be manipulated by directly changingits fields (such asElement.text
), adding and modifying attributes(Element.set()
method), as well as adding new children (for examplewithElement.append()
).
Let’s say we want to add one to each country’s rank, and add anupdated
attribute to the rank element:
>>>forrankinroot.iter('rank'):...new_rank=int(rank.text)+1...rank.text=str(new_rank)...rank.set('updated','yes')...>>>tree.write('output.xml')
Our XML now looks like this:
<?xml version="1.0"?><data><countryname="Liechtenstein"><rankupdated="yes">2</rank><year>2008</year><gdppc>141100</gdppc><neighborname="Austria"direction="E"/><neighborname="Switzerland"direction="W"/></country><countryname="Singapore"><rankupdated="yes">5</rank><year>2011</year><gdppc>59900</gdppc><neighborname="Malaysia"direction="N"/></country><countryname="Panama"><rankupdated="yes">69</rank><year>2011</year><gdppc>13600</gdppc><neighborname="Costa Rica"direction="W"/><neighborname="Colombia"direction="E"/></country></data>
We can remove elements usingElement.remove()
. Let’s say we want toremove all countries with a rank higher than 50:
>>>forcountryinroot.findall('country'):...# using root.findall() to avoid removal during traversal...rank=int(country.find('rank').text)...ifrank>50:...root.remove(country)...>>>tree.write('output.xml')
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 withroot.findall()
, and only then iterates over the list of matches.
Our XML now looks like this:
<?xml version="1.0"?><data><countryname="Liechtenstein"><rankupdated="yes">2</rank><year>2008</year><gdppc>141100</gdppc><neighborname="Austria"direction="E"/><neighborname="Switzerland"direction="W"/></country><countryname="Singapore"><rankupdated="yes">5</rank><year>2011</year><gdppc>59900</gdppc><neighborname="Malaysia"direction="N"/></country></data>
Building XML documents¶
TheSubElement()
function also provides a convenient way to create newsub-elements for a given element:
>>>a=ET.Element('a')>>>b=ET.SubElement(a,'b')>>>c=ET.SubElement(a,'c')>>>d=ET.SubElement(c,'d')>>>ET.dump(a)<a><b /><c><d /></c></a>
Parsing XML with Namespaces¶
If the XML input hasnamespaces, tags and attributeswith prefixes in the formprefix:sometag
get expanded to{uri}sometag
where theprefix is replaced by the fullURI.Also, if there is adefault namespace,that full URI gets prepended to all of the non-prefixed tags.
Here is an XML example that incorporates two namespaces, one with theprefix “fictional” and the other serving as the default namespace:
<?xml version="1.0"?><actorsxmlns:fictional="http://characters.example.com"xmlns="http://people.example.com"><actor><name>JohnCleese</name><fictional:character>Lancelot</fictional:character><fictional:character>ArchieLeach</fictional:character></actor><actor><name>EricIdle</name><fictional:character>SirRobin</fictional:character><fictional:character>Gunther</fictional:character><fictional:character>CommanderClement</fictional:character></actor></actors>
One way to search and explore this XML example is to manually add theURI to every tag or attribute in the xpath of afind()
orfindall()
:
root=fromstring(xml_text)foractorinroot.findall('{http://people.example.com}actor'):name=actor.find('{http://people.example.com}name')print(name.text)forcharinactor.findall('{http://characters.example.com}character'):print(' |-->',char.text)
A better way to search the namespaced XML example is to create adictionary with your own prefixes and use those in the search functions:
ns={'real_person':'http://people.example.com','role':'http://characters.example.com'}foractorinroot.findall('real_person:actor',ns):name=actor.find('real_person:name',ns)print(name.text)forcharinactor.findall('role:character',ns):print(' |-->',char.text)
These two approaches both output:
JohnCleese|-->Lancelot|-->ArchieLeachEricIdle|-->SirRobin|-->Gunther|-->CommanderClement
XPath support¶
This module provides limited support forXPath expressions for locating elements in atree. The goal is to support a small subset of the abbreviated syntax; a fullXPath engine is outside the scope of the module.
Example¶
Here’s an example that demonstrates some of the XPath capabilities of themodule. We’ll be using thecountrydata
XML document from theParsing XML section:
importxml.etree.ElementTreeasETroot=ET.fromstring(countrydata)# Top-level elementsroot.findall(".")# All 'neighbor' grand-children of 'country' children of the top-level# elementsroot.findall("./country/neighbor")# Nodes with name='Singapore' that have a 'year' childroot.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 parentroot.findall(".//neighbor[2]")
For XML with namespaces, use the usual qualified{namespace}tag
notation:
# All dublin-core "title" tags in the documentroot.findall(".//{http://purl.org/dc/elements/1.1/}title")
Supported XPath syntax¶
Syntax | Meaning |
---|---|
| Selects all child elements with the given tag.For example, Changed in version 3.8:Support for star-wildcards was added. |
| Selects all child elements, including comments andprocessing instructions. For example, |
| Selects the current node. This is mostly usefulat the beginning of the path, to indicate that it’sa relative path. |
| Selects all subelements, on all levels beneath thecurrent element. For example, |
| Selects the parent element. Returns |
| Selects all elements that have the given attribute. |
| Selects all elements for which the given attributehas the given value. The value cannot containquotes. |
| Selects all elements for which the given attributedoes not have the given value. The value cannotcontain quotes. Added in version 3.10. |
| Selects all elements that have a child named |
| Selects all elements whose complete text content,including descendants, equals the given Added in version 3.7. |
| Selects all elements whose complete text content,including descendants, does not equal the given Added in version 3.10. |
| Selects all elements that have a child named |
| Selects all elements that have a child named Added in version 3.10. |
| Selects all elements that are located at the givenposition. The position can be either an integer(1 is the first position), the expression |
Predicates (expressions within square brackets) must be preceded by a tagname, an asterisk, or another predicate.position
predicates must bepreceded by a tag name.
Reference¶
Functions¶
- xml.etree.ElementTree.canonicalize(xml_data=None,*,out=None,from_file=None,**options)¶
C14N 2.0 transformation function.
Canonicalization is a way to normalise XML output in a way that allowsbyte-by-byte comparisons and digital signatures. It reduces the freedomthat XML serializers have and instead generates a more constrained XMLrepresentation. The main restrictions regard the placement of namespacedeclarations, the ordering of attributes, and ignorable whitespace.
This function takes an XML data string (xml_data) or a file path orfile-like object (from_file) as input, converts it to the canonicalform, and writes it out using theout 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
utf-8
encoding.Typical uses:
xml_data="<root>...</root>"print(canonicalize(xml_data))withopen("c14n_output.xml",mode='w',encoding='utf-8')asout_file:canonicalize(xml_data,out=out_file)withopen("c14n_output.xml",mode='w',encoding='utf-8')asout_file:canonicalize(from_file="inputfile.xml",out=out_file)
The configurationoptions are as follows:
with_comments: set to true to include comments (default: false)
- strip_text: set to true to strip whitespace before and after text content
(default: false)
- rewrite_prefixes: set to true to replace namespace prefixes by “n{number}”
(default: false)
- qname_aware_tags: a set of qname aware tag names in which prefixes
should be replaced in text content (default: empty)
- qname_aware_attrs: a set of qname aware attribute names in which prefixes
should be replaced in text content (default: empty)
exclude_attrs: a set of attribute names that should not be serialised
exclude_tags: a set of tag names that should not be serialised
In the option list above, “a set” refers to any collection or iterable ofstrings, no ordering is expected.
Added in version 3.8.
- xml.etree.ElementTree.Comment(text=None)¶
Comment element factory. This factory function creates a special elementthat will be serialized as an XML comment by the standard serializer. Thecomment string can be either a bytestring or a Unicode string.text is astring containing the comment string. Returns an element instancerepresenting a comment.
Note that
XMLParser
skips over comments in the inputinstead of creating comment objects for them. AnElementTree
willonly contain comment nodes if they have been inserted into tothe tree using one of theElement
methods.
- xml.etree.ElementTree.dump(elem)¶
Writes an element tree or element structure to sys.stdout. This functionshould be used for debugging only.
The exact output format is implementation dependent. In this version, it’swritten as an ordinary XML file.
elem is an element tree or an individual element.
Changed in version 3.8:The
dump()
function now preserves the attribute order specifiedby the user.
- xml.etree.ElementTree.fromstring(text,parser=None)¶
Parses an XML section from a string constant. Same as
XML()
.textis a string containing XML data.parser is an optional parser instance.If not given, the standardXMLParser
parser is used.Returns anElement
instance.
- xml.etree.ElementTree.fromstringlist(sequence,parser=None)¶
Parses an XML document from a sequence of string fragments.sequence is alist or other sequence containing XML data fragments.parser is anoptional parser instance. If not given, the standard
XMLParser
parser is used. Returns anElement
instance.Added in version 3.2.
- xml.etree.ElementTree.indent(tree,space=' ',level=0)¶
Appends whitespace to the subtree to indent the tree visually.This can be used to generate pretty-printed XML output.tree can be an Element or ElementTree.space is the whitespacestring that will be inserted for each indentation level, two spacecharacters by default. For indenting partial subtrees inside of analready indented tree, pass the initial indentation level aslevel.
Added in version 3.9.
- xml.etree.ElementTree.iselement(element)¶
Check if an object appears to be a valid element object.element is anelement instance. Return
True
if this is an element object.
- xml.etree.ElementTree.iterparse(source,events=None,parser=None)¶
Parses an XML section into an element tree incrementally, and reports what’sgoing on to the user.source is a filename orfile objectcontaining XML data.events is a sequence of events to report back. Thesupported events are the strings
"start"
,"end"
,"comment"
,"pi"
,"start-ns"
and"end-ns"
(the “ns” events are used to get detailed namespaceinformation). Ifevents is omitted, only"end"
events are reported.parser is an optional parser instance. If not given, the standardXMLParser
parser is used.parser must be a subclass ofXMLParser
and can only use the defaultTreeBuilder
as atarget. Returns aniterator providing(event,elem)
pairs;it has aroot
attribute that references the root element of theresulting XML tree oncesource is fully read.The iterator has theclose()
method that closes the internalfile object ifsource is a filename.Note that while
iterparse()
builds the tree incrementally, it issuesblocking reads onsource (or the file it names). As such, it’s unsuitablefor applications where blocking reads can’t be made. For fully non-blockingparsing, seeXMLPullParser
.Note
iterparse()
only guarantees that it has seen the “>” character of astarting tag when it emits a “start” event, so the attributes are defined,but the contents of the text and tail attributes are undefined at thatpoint. The same applies to the element children; they may or may not bepresent.If you need a fully populated element, look for “end” events instead.
Deprecated since version 3.4:Theparser argument.
Changed in version 3.8:The
comment
andpi
events were added.Changed in version 3.13:Added the
close()
method.
- xml.etree.ElementTree.parse(source,parser=None)¶
Parses an XML section into an element tree.source is a filename or fileobject containing XML data.parser is an optional parser instance. Ifnot given, the standard
XMLParser
parser is used. Returns anElementTree
instance.
- xml.etree.ElementTree.ProcessingInstruction(target,text=None)¶
PI element factory. This factory function creates a special element thatwill be serialized as an XML processing instruction.target is a stringcontaining the PI target.text is a string containing the PI contents, ifgiven. Returns an element instance, representing a processing instruction.
Note that
XMLParser
skips over processing instructionsin the input instead of creating PI objects for them. AnElementTree
will only contain processing instruction nodes ifthey have been inserted into to the tree using one of theElement
methods.
- xml.etree.ElementTree.register_namespace(prefix,uri)¶
Registers a namespace prefix. The registry is global, and any existingmapping for either the given prefix or the namespace URI will be removed.prefix is a namespace prefix.uri is a namespace uri. Tags andattributes in this namespace will be serialized with the given prefix, if atall possible.
Added in version 3.2.
- xml.etree.ElementTree.SubElement(parent,tag,attrib={},**extra)¶
Subelement factory. This function creates an element instance, and appendsit to an existing element.
The element name, attribute names, and attribute values can be eitherbytestrings or Unicode strings.parent is the parent element.tag isthe subelement name.attrib is an optional dictionary, containing elementattributes.extra contains additional attributes, given as keywordarguments. Returns an element instance.
- xml.etree.ElementTree.tostring(element,encoding='us-ascii',method='xml',*,xml_declaration=None,default_namespace=None,short_empty_elements=True)¶
Generates a string representation of an XML element, including allsubelements.element is an
Element
instance.encoding[1] isthe output encoding (default is US-ASCII). Useencoding="unicode"
togenerate a Unicode string (otherwise, a bytestring is generated).methodis either"xml"
,"html"
or"text"
(default is"xml"
).xml_declaration,default_namespace andshort_empty_elements has the samemeaning as inElementTree.write()
. Returns an (optionally) encoded stringcontaining the XML data.Changed in version 3.4:Added theshort_empty_elements parameter.
Changed in version 3.8:Added thexml_declaration anddefault_namespace parameters.
Changed in version 3.8:The
tostring()
function now preserves the attribute orderspecified by the user.
- xml.etree.ElementTree.tostringlist(element,encoding='us-ascii',method='xml',*,xml_declaration=None,default_namespace=None,short_empty_elements=True)¶
Generates a string representation of an XML element, including allsubelements.element is an
Element
instance.encoding[1] isthe output encoding (default is US-ASCII). Useencoding="unicode"
togenerate a Unicode string (otherwise, a bytestring is generated).methodis either"xml"
,"html"
or"text"
(default is"xml"
).xml_declaration,default_namespace andshort_empty_elements has the samemeaning as inElementTree.write()
. Returns a list of (optionally) encodedstrings containing the XML data. It does not guarantee any specific sequence,except thatb"".join(tostringlist(element))==tostring(element)
.Added in version 3.2.
Changed in version 3.4:Added theshort_empty_elements parameter.
Changed in version 3.8:Added thexml_declaration anddefault_namespace parameters.
Changed in version 3.8:The
tostringlist()
function now preserves the attribute orderspecified by the user.
- xml.etree.ElementTree.XML(text,parser=None)¶
Parses an XML section from a string constant. This function can be used toembed “XML literals” in Python code.text is a string containing XMLdata.parser is an optional parser instance. If not given, the standard
XMLParser
parser is used. Returns anElement
instance.
- xml.etree.ElementTree.XMLID(text,parser=None)¶
Parses an XML section from a string constant, and also returns a dictionarywhich maps from element id:s to elements.text is a string containing XMLdata.parser is an optional parser instance. If not given, the standard
XMLParser
parser is used. Returns a tuple containing anElement
instance and a dictionary.
XInclude support¶
This module provides limited support forXInclude directives, via thexml.etree.ElementInclude
helper module. This module can be used to insert subtrees and text strings into element trees, based on information in the tree.
Example¶
Here’s an example that demonstrates use of the XInclude module. To include an XML document in the current document, use the{http://www.w3.org/2001/XInclude}include
element and set theparse attribute to"xml"
, and use thehref attribute to specify the document to include.
<?xml version="1.0"?><documentxmlns:xi="http://www.w3.org/2001/XInclude"><xi:includehref="source.xml"parse="xml"/></document>
By default, thehref 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.
To process this file, load it as usual, and pass the root element to thexml.etree.ElementTree
module:
fromxml.etreeimportElementTree,ElementIncludetree=ElementTree.parse("document.xml")root=tree.getroot()ElementInclude.include(root)
The ElementInclude module replaces the{http://www.w3.org/2001/XInclude}include
element with the root element from thesource.xml document. The result might look something like this:
<documentxmlns:xi="http://www.w3.org/2001/XInclude"><para>Thisisaparagraph.</para></document>
If theparse attribute is omitted, it defaults to “xml”. The href attribute is required.
To include a text document, use the{http://www.w3.org/2001/XInclude}include
element, and set theparse attribute to “text”:
<?xml version="1.0"?><documentxmlns:xi="http://www.w3.org/2001/XInclude">Copyright(c)<xi:includehref="year.txt"parse="text"/>.</document>
The result might look something like:
<documentxmlns:xi="http://www.w3.org/2001/XInclude">Copyright(c)2003.</document>
Reference¶
Functions¶
- xml.etree.ElementInclude.default_loader(href,parse,encoding=None)¶
Default loader. This default loader reads an included resource from disk.href is a URL.parse is for parse mode either “xml” or “text”.encoding is an optional text encoding. If not given, encoding is
utf-8
.Returns the expanded resource.If the parse mode is"xml"
, this is anElement
instance.If the parse mode is"text"
, this is a string.If the loader fails, it can returnNone
or raise an exception.
- xml.etree.ElementInclude.include(elem,loader=None,base_url=None,max_depth=6)¶
This function expands XInclude directives in-place in tree pointed byelem.elem is either the root
Element
or anElementTree
instance to find such element.loader is an optional resource loader. If omitted, it defaults todefault_loader()
.If given, it should be a callable that implements the same interface asdefault_loader()
.base_url is base URL of the original file, to resolverelative include file references.max_depth is the maximum number of recursiveinclusions. Limited to reduce the risk of malicious content explosion.PassNone
to disable the limitation.Changed in version 3.9:Added thebase_url andmax_depth parameters.
Element Objects¶
- classxml.etree.ElementTree.Element(tag,attrib={},**extra)¶
Element class. This class defines the Element interface, and provides areference implementation of this interface.
The element name, attribute names, and attribute values can be eitherbytestrings or Unicode strings.tag is the element name.attrib isan optional dictionary, containing element attributes.extra containsadditional attributes, given as keyword arguments.
- tag¶
A string identifying what kind of data this element represents (theelement type, in other words).
- text¶
- tail¶
These attributes can be used to hold additional data associated withthe element. Their values are usually strings but may be anyapplication-specific object. If the element is created froman XML file, thetext attribute holds either the text betweenthe element’s start tag and its first child or end tag, or
None
, andthetail attribute holds either the text between the element’send tag and the next tag, orNone
. For the XML data<a><b>1<c>2<d/>3</c></b>4</a>
thea element has
None
for bothtext andtail attributes,theb element hastext"1"
andtail"4"
,thec element hastext"2"
andtailNone
,and thed element hastextNone
andtail"3"
.To collect the inner text of an element, see
itertext()
, forexample"".join(element.itertext())
.Applications may store arbitrary objects in these attributes.
- attrib¶
A dictionary containing the element’s attributes. Note that while theattrib value is always a real mutable Python dictionary, an ElementTreeimplementation may choose to use another internal representation, andcreate the dictionary only if someone asks for it. To take advantage ofsuch implementations, use the dictionary methods below whenever possible.
The following dictionary-like methods work on the element attributes.
- clear()¶
Resets an element. This function removes all subelements, clears allattributes, and sets the text and tail attributes to
None
.
- get(key,default=None)¶
Gets the element attribute namedkey.
Returns the attribute value, ordefault if the attribute was not found.
- items()¶
Returns the element attributes as a sequence of (name, value) pairs. Theattributes are returned in an arbitrary order.
- keys()¶
Returns the elements attribute names as a list. The names are returnedin an arbitrary order.
- set(key,value)¶
Set the attributekey on the element tovalue.
The following methods work on the element’s children (subelements).
- append(subelement)¶
Adds the elementsubelement to the end of this element’s internal listof subelements. Raises
TypeError
ifsubelement is not anElement
.
- extend(subelements)¶
Appendssubelements from an iterable of elements.Raises
TypeError
if a subelement is not anElement
.Added in version 3.2.
- find(match,namespaces=None)¶
Finds the first subelement matchingmatch.match may be a tag nameor apath. Returns an element instanceor
None
.namespaces is an optional mapping from namespace prefixto full name. Pass''
as prefix to move all unprefixed tag namesin the expression into the given namespace.
- findall(match,namespaces=None)¶
Finds all matching subelements, by tag name orpath. Returns a list containing all matchingelements in document order.namespaces is an optional mapping fromnamespace prefix to full name. Pass
''
as prefix to move allunprefixed tag names in the expression into the given namespace.
- findtext(match,default=None,namespaces=None)¶
Finds text for the first subelement matchingmatch.match may bea tag name or apath. Returns the text contentof the first matching element, ordefault if no element was found.Note that if the matching element has no text content an empty stringis returned.namespaces is an optional mapping from namespace prefixto full name. Pass
''
as prefix to move all unprefixed tag namesin the expression into the given namespace.
- insert(index,subelement)¶
Insertssubelement at the given position in this element. Raises
TypeError
ifsubelement is not anElement
.
- iter(tag=None)¶
Creates a treeiterator with the current element as the root.The iterator iterates over this element and all elements below it, indocument (depth first) order. Iftag is not
None
or'*'
, onlyelements whose tag equalstag are returned from the iterator. If thetree structure is modified during iteration, the result is undefined.Added in version 3.2.
- iterfind(match,namespaces=None)¶
Finds all matching subelements, by tag name orpath. Returns an iterable yielding allmatching elements in document order.namespaces is an optional mappingfrom namespace prefix to full name.
Added in version 3.2.
- itertext()¶
Creates a text iterator. The iterator loops over this element and allsubelements, in document order, and returns all inner text.
Added in version 3.2.
- makeelement(tag,attrib)¶
Creates a new element object of the same type as this element. Do notcall this method, use the
SubElement()
factory function instead.
- remove(subelement)¶
Removessubelement from the element. Unlike the find* methods thismethod compares elements based on the instance identity, not on tag valueor contents.
Element
objects also support the following sequence type methodsfor working with subelements:__delitem__()
,__getitem__()
,__setitem__()
,__len__()
.Caution: Elements with no subelements will test as
False
. In a futurerelease of Python, all elements will test asTrue
regardless of whethersubelements exist. Instead, prefer explicitlen(elem)
orelemisnotNone
tests.:element=root.find('foo')ifnotelement:# careful!print("element not found, or element has no subelements")ifelementisNone:print("element not found")
Changed in version 3.12:Testing the truth value of an Element emits
DeprecationWarning
.Prior to Python 3.8, the serialisation order of the XML attributes ofelements was artificially made predictable by sorting the attributes bytheir name. Based on the now guaranteed ordering of dicts, this arbitraryreordering was removed in Python 3.8 to preserve the order in whichattributes were originally parsed or created by user code.
In general, user code should try not to depend on a specific ordering ofattributes, given that theXML Information Set explicitly excludes the attributeorder from conveying information. Code should be prepared to deal withany ordering on input. In cases where deterministic XML output is required,e.g. for cryptographic signing or test data sets, canonical serialisationis available with the
canonicalize()
function.In cases where canonical output is not applicable but a specific attributeorder is still desirable on output, code should aim for creating theattributes directly in the desired order, to avoid perceptual mismatchesfor readers of the code. In cases where this is difficult to achieve, arecipe like the following can be applied prior to serialisation to enforcean order independently from the Element creation:
defreorder_attributes(root):forelinroot.iter():attrib=el.attribiflen(attrib)>1:# adjust attribute order, e.g. by sortingattribs=sorted(attrib.items())attrib.clear()attrib.update(attribs)
ElementTree Objects¶
- classxml.etree.ElementTree.ElementTree(element=None,file=None)¶
ElementTree wrapper class. This class represents an entire elementhierarchy, and adds some extra support for serialization to and fromstandard XML.
element is the root element. The tree is initialized with the contentsof the XMLfile if given.
- _setroot(element)¶
Replaces the root element for this tree. This discards the currentcontents of the tree, and replaces it with the given element. Use withcare.element is an element instance.
- find(match,namespaces=None)¶
Same as
Element.find()
, starting at the root of the tree.
- findall(match,namespaces=None)¶
Same as
Element.findall()
, starting at the root of the tree.
- findtext(match,default=None,namespaces=None)¶
Same as
Element.findtext()
, starting at the root of the tree.
- getroot()¶
Returns the root element for this tree.
- iter(tag=None)¶
Creates and returns a tree iterator for the root element. The iteratorloops over all elements in this tree, in section order.tag is the tagto look for (default is to return all elements).
- iterfind(match,namespaces=None)¶
Same as
Element.iterfind()
, starting at the root of the tree.Added in version 3.2.
- parse(source,parser=None)¶
Loads an external XML section into this element tree.source is a filename orfile object.parser is an optional parser instance.If not given, the standard
XMLParser
parser is used. Returns thesection 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 afile object opened for writing.encoding[1] is the outputencoding (default is US-ASCII).xml_declaration controls if an XML declaration should be added to thefile. Use
False
for never,True
for always,None
for only if not US-ASCII or UTF-8 or Unicode (default isNone
).default_namespace sets the default XML namespace (for “xmlns”).method is either"xml"
,"html"
or"text"
(default is"xml"
).The keyword-onlyshort_empty_elements parameter controls the formattingof elements that contain no content. IfTrue
(the default), they areemitted as a single self-closed tag, otherwise they are emitted as a pairof start/end tags.The output is either a string (
str
) or binary (bytes
).This is controlled by theencoding argument. Ifencoding is"unicode"
, the output is a string; otherwise, it’s binary. Note thatthis may conflict with the type offile if it’s an openfile object; make sure you do not try to write a string to abinary stream and vice versa.Changed in version 3.4:Added theshort_empty_elements parameter.
Changed in version 3.8:The
write()
method now preserves the attribute order specifiedby the user.
This is the XML file that is going to be manipulated:
<html><head><title>Examplepage</title></head><body><p>Movedto<ahref="http://example.org/">example.org</a>or<ahref="http://example.com/">example.com</a>.</p></body></html>
Example of changing the attribute “target” of every link in first paragraph:
>>>fromxml.etree.ElementTreeimportElementTree>>>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>]>>>foriinlinks:# Iterates through all found links...i.attrib["target"]="blank"...>>>tree.write("output.xhtml")
QName Objects¶
- classxml.etree.ElementTree.QName(text_or_uri,tag=None)¶
QName wrapper. This can be used to wrap a QName attribute value, in orderto get proper namespace handling on output.text_or_uri is a stringcontaining the QName value, in the form {uri}local, or, if the tag argumentis given, the URI part of a QName. Iftag is given, the first argument isinterpreted as a URI, and this argument is interpreted as a local name.
QName
instances are opaque.
TreeBuilder Objects¶
- classxml.etree.ElementTree.TreeBuilder(element_factory=None,*,comment_factory=None,pi_factory=None,insert_comments=False,insert_pis=False)¶
Generic element structure builder. This builder converts a sequence ofstart, data, end, comment and pi method calls to a well-formed elementstructure. You can use this class to build an element structure usinga custom XML parser, or a parser for some other XML-like format.
element_factory, when given, must be a callable accepting two positionalarguments: a tag and a dict of attributes. It is expected to return a newelement instance.
Thecomment_factory andpi_factory functions, when given, should behavelike the
Comment()
andProcessingInstruction()
functions tocreate comments and processing instructions. When not given, the defaultfactories will be used. Wheninsert_comments and/orinsert_pis is true,comments/pis will be inserted into the tree if they appear within the rootelement (but not outside of it).- close()¶
Flushes the builder buffers, and returns the toplevel documentelement. Returns an
Element
instance.
- data(data)¶
Adds text to the current element.data is a string. This should beeither a bytestring, or a Unicode string.
- end(tag)¶
Closes the current element.tag is the element name. Returns theclosed element.
- start(tag,attrs)¶
Opens a new element.tag is the element name.attrs is a dictionarycontaining element attributes. Returns the opened element.
- comment(text)¶
Creates a comment with the giventext. If
insert_comments
is true,this will also add it to the tree.Added in version 3.8.
- pi(target,text)¶
Creates a process instruction with the giventarget name andtext.If
insert_pis
is true, this will also add it to the tree.Added in version 3.8.
In addition, a custom
TreeBuilder
object can provide thefollowing methods:- doctype(name,pubid,system)¶
Handles a doctype declaration.name is the doctype name.pubid isthe public identifier.system is the system identifier. This methoddoes not exist on the default
TreeBuilder
class.Added in version 3.2.
- start_ns(prefix,uri)¶
Is called whenever the parser encounters a new namespace declaration,before the
start()
callback for the opening element that defines it.prefix is''
for the default namespace and the declarednamespace prefix name otherwise.uri is the namespace URI.Added in version 3.8.
- end_ns(prefix)¶
Is called after the
end()
callback of an element that declareda namespace prefix mapping, with the name of theprefix that wentout of scope.Added in version 3.8.
- classxml.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)¶
AC14N 2.0 writer. Arguments are thesame as for the
canonicalize()
function. This class does not build atree but translates the callback events directly into a serialised formusing thewrite function.Added in version 3.8.
XMLParser Objects¶
- classxml.etree.ElementTree.XMLParser(*,target=None,encoding=None)¶
This class is the low-level building block of the module. It uses
xml.parsers.expat
for efficient, event-based parsing of XML. It canbe fed XML data incrementally with thefeed()
method, and parsingevents are translated to a push API - by invoking callbacks on thetargetobject. Iftarget is omitted, the standardTreeBuilder
is used.Ifencoding[1] is given, the value overrides theencoding specified in the XML file.Changed in version 3.8:Parameters are nowkeyword-only.Thehtml argument is no longer supported.
- close()¶
Finishes feeding data to the parser. Returns the result of calling the
close()
method of thetarget passed during construction; by default,this is the toplevel document element.
- feed(data)¶
Feeds data to the parser.data is encoded data.
- flush()¶
Triggers parsing of any previously fed unparsed data, which can beused to ensure more immediate feedback, in particular with Expat >=2.6.0.The implementation of
flush()
temporarily disables reparse deferralwith Expat (if currently enabled) and triggers a reparse.Disabling reparse deferral has security consequences; please seexml.parsers.expat.xmlparser.SetReparseDeferralEnabled()
for details.Note that
flush()
has been backported to some prior releases ofCPython as a security fix. Check for availability offlush()
usinghasattr()
if used in code running across a variety of Pythonversions.Added in version 3.13.
XMLParser.feed()
callstarget'sstart(tag,attrs_dict)
methodfor each opening tag, itsend(tag)
method for each closing tag, and datais processed by methoddata(data)
. For further supported callbackmethods, see theTreeBuilder
class.XMLParser.close()
callstarget's methodclose()
.XMLParser
can be used not only forbuilding a tree structure. This is an example of counting the maximum depthof an XML file:>>>fromxml.etree.ElementTreeimportXMLParser>>>classMaxDepth:# The target object of the parser...maxDepth=0...depth=0...defstart(self,tag,attrib):# Called for each opening tag....self.depth+=1...ifself.depth>self.maxDepth:...self.maxDepth=self.depth...defend(self,tag):# Called for each closing tag....self.depth-=1...defdata(self,data):...pass# We do not need to do anything with data....defclose(self):# Called when all data has been parsed....returnself.maxDepth...>>>target=MaxDepth()>>>parser=XMLParser(target=target)>>>exampleXml="""...<a>... <b>... </b>... <b>... <c>... <d>... </d>... </c>... </b>...</a>""">>>parser.feed(exampleXml)>>>parser.close()4
XMLPullParser Objects¶
- classxml.etree.ElementTree.XMLPullParser(events=None)¶
A pull parser suitable for non-blocking applications. Its input-side API issimilar to that of
XMLParser
, but instead of pushing calls to acallback target,XMLPullParser
collects an internal list of parsingevents and lets the user read from it.events is a sequence of events toreport back. The supported events are the strings"start"
,"end"
,"comment"
,"pi"
,"start-ns"
and"end-ns"
(the “ns” eventsare used to get detailed namespace information). Ifevents is omitted,only"end"
events are reported.- feed(data)¶
Feed the given bytes data to the parser.
- flush()¶
Triggers parsing of any previously fed unparsed data, which can beused to ensure more immediate feedback, in particular with Expat >=2.6.0.The implementation of
flush()
temporarily disables reparse deferralwith Expat (if currently enabled) and triggers a reparse.Disabling reparse deferral has security consequences; please seexml.parsers.expat.xmlparser.SetReparseDeferralEnabled()
for details.Note that
flush()
has been backported to some prior releases ofCPython as a security fix. Check for availability offlush()
usinghasattr()
if used in code running across a variety of Pythonversions.Added in version 3.13.
- close()¶
Signal the parser that the data stream is terminated. Unlike
XMLParser.close()
, this method always returnsNone
.Any events not yet retrieved when the parser is closed can still beread withread_events()
.
- read_events()¶
Return an iterator over the events which have been encountered in thedata fed to theparser. The iterator yields
(event,elem)
pairs, whereevent is astring representing the type of event (e.g."end"
) andelem is theencounteredElement
object, or other context value as follows.start
,end
: the current Element.comment
,pi
: the current comment / processing instructionstart-ns
: a tuple(prefix,uri)
naming the declared namespacemapping.end-ns
:None
(this may change in a future version)
Events provided in a previous call to
read_events()
will not beyielded again. Events are consumed from the internal queue only whenthey are retrieved from the iterator, so multiple readers iterating inparallel over iterators obtained fromread_events()
will haveunpredictable results.
Note
XMLPullParser
only guarantees that it has seen the “>”character of a starting tag when it emits a “start” event, so theattributes are defined, but the contents of the text and tail attributesare undefined at that point. The same applies to the element children;they may or may not be present.If you need a fully populated element, look for “end” events instead.
Added in version 3.4.
Changed in version 3.8:The
comment
andpi
events were added.
Exceptions¶
- classxml.etree.ElementTree.ParseError¶
XML parse error, raised by the various parsing methods in this module whenparsing fails. The string representation of an instance of this exceptionwill contain a user-friendly error message. In addition, it will havethe following attributes available:
- code¶
A numeric error code from the expat parser. See the documentation of
xml.parsers.expat
for the list of error codes and their meanings.
- position¶
A tuple ofline,column numbers, specifying where the error occurred.
Footnotes
[1](1,2,3,4)The encoding string included in XML output should conform to theappropriate standards. For example, “UTF-8” is valid, but “UTF8” isnot. Seehttps://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDeclandhttps://www.iana.org/assignments/character-sets/character-sets.xhtml.