20.5. xml.etree.ElementTree — The ElementTree XML API (2024)

documentation.HELP! Python 3.6.3 Documentation

Python 3.6.3

previous page next page

Navigation

  • index
  • modules |
  • next |
  • previous |
  • 20.5. xml.etree.ElementTree — The ElementTree XML API (1)
  • Python »
  • 3.6.3 Documentation »
  • The Python Standard Library »
  • 20. Structured Markup Processing Tools »

Source code: Lib/xml/etree/ElementTree.py

The xml.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.The xml.etree.cElementTree module is deprecated.

Warning

The xml.etree.ElementTree module is not secure againstmaliciously constructed data. If you need to parse untrusted orunauthenticated data see XML vulnerabilities.

20.5.1. Tutorial

This is a short tutorial for using xml.etree.ElementTree (ET inshort). The goal is to demonstrate some of the building blocks and basicconcepts of the module.

20.5.1.1. 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 the ElementTree level. Interactions with a single XML elementand its sub-elements are done on the Element level.

20.5.1.2. Parsing XML

We’ll be using the following XML document as the sample data for this section:

<?xml version="1.0"?><data> <country name="Liechtenstein"> <rank>1</rank> <year>2008</year> <gdppc>141100</gdppc> <neighbor name="Austria" direction="E"/> <neighbor name="Switzerland" direction="W"/> </country> <country name="Singapore"> <rank>4</rank> <year>2011</year> <gdppc>59900</gdppc> <neighbor name="Malaysia" direction="N"/> </country> <country name="Panama"> <rank>68</rank> <year>2011</year> <gdppc>13600</gdppc> <neighbor name="Costa Rica" direction="W"/> <neighbor name="Colombia" direction="E"/> </country></data>

We can import this data by reading from a file:

import xml.etree.ElementTree as ETtree = 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 an Element,which is the root element of the parsed tree. Other parsing functions maycreate an ElementTree. Check the documentation to be sure.

As an Element, root has a tag and a dictionary of attributes:

>>> root.tag'data'>>> root.attrib{}

It also has children nodes over which we can iterate:

>>> for child in root:...  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 acustom TreeBuilder instance to the XMLParserconstructor.

20.5.1.3. 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 constructed Element objects.

The most powerful tool for doing this is XMLPullParser. It does notrequire a blocking read to obtain the XML data, and is instead fed with dataincrementally with XMLPullParser.feed() calls. To get the parsed XMLelements, call XMLPullParser.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>')>>> for event, elem in parser.read_events():...  print(event)...  print(elem.tag, 'text=', elem.text)...end

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 lookat iterparse(). It can be useful when you’re reading a large XML documentand don’t want to hold it wholly in memory.

20.5.1.4. 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():

>>> 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'}

Element.findall() finds only elements with a tag which are directchildren of the current element. Element.find() finds the first childwith a particular tag, and Element.text accesses the element’s textcontent. Element.get() accesses the element’s attributes:

>>> for country in root.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 byusing XPath.

20.5.1.5. Modifying an XML File

ElementTree provides a simple way to build XML documents and write them to files.The ElementTree.write() method serves this purpose.

Once created, an Element object may be manipulated by directly changingits fields (such as Element.text), adding and modifying attributes(Element.set() method), as well as adding new children (for examplewith Element.append()).

Let’s say we want to add one to each country’s rank, and add an updatedattribute to the rank element:

>>> for rank in root.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> <country name="Liechtenstein"> <rank updated="yes">2</rank> <year>2008</year> <gdppc>141100</gdppc> <neighbor name="Austria" direction="E"/> <neighbor name="Switzerland" direction="W"/> </country> <country name="Singapore"> <rank updated="yes">5</rank> <year>2011</year> <gdppc>59900</gdppc> <neighbor name="Malaysia" direction="N"/> </country> <country name="Panama"> <rank updated="yes">69</rank> <year>2011</year> <gdppc>13600</gdppc> <neighbor name="Costa Rica" direction="W"/> <neighbor name="Colombia" direction="E"/> </country></data>

We can remove elements using Element.remove(). Let’s say we want toremove all countries with a rank higher than 50:

>>> for country in root.findall('country'):...  rank = int(country.find('rank').text)...  if rank > 50:...  root.remove(country)...>>> tree.write('output.xml')

Our XML now looks like this:

<?xml version="1.0"?><data> <country name="Liechtenstein"> <rank updated="yes">2</rank> <year>2008</year> <gdppc>141100</gdppc> <neighbor name="Austria" direction="E"/> <neighbor name="Switzerland" direction="W"/> </country> <country name="Singapore"> <rank updated="yes">5</rank> <year>2011</year> <gdppc>59900</gdppc> <neighbor name="Malaysia" direction="N"/> </country></data>

20.5.1.6. Building XML documents

The SubElement() 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>

20.5.1.7. Parsing XML with Namespaces

If the XML input has namespaces, tags and attributeswith prefixes in the form prefix:sometag get expanded to{uri}sometag where the prefix is replaced by the full URI.Also, if there is a default 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"?><actors xmlns:fictional="http://characters.example.com" xmlns="http://people.example.com"> <actor> <name>John Cleese</name> <fictional:character>Lancelot</fictional:character> <fictional:character>Archie Leach</fictional:character> </actor> <actor> <name>Eric Idle</name> <fictional:character>Sir Robin</fictional:character> <fictional:character>Gunther</fictional:character> <fictional:character>Commander Clement</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() or findall():

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(' |-->', 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'}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(' |-->', char.text)

These two approaches both output:

John Cleese |--> Lancelot |--> Archie LeachEric Idle |--> Sir Robin |--> Gunther |--> Commander Clement

20.5.1.8. Additional resources

See http://effbot.org/zone/element-index.htm for tutorials and links to otherdocs.

20.5.2. 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.

20.5.2.1. Example

Here’s an example that demonstrates some of the XPath capabilities of themodule. We’ll be using the countrydata XML document from theParsing XML section:

import xml.etree.ElementTree as ETroot = 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]")

20.5.2.2. Supported XPath syntax

SyntaxMeaning
tagSelects all child elements with the given tag.For example, spam selects all child elementsnamed spam, and spam/egg selects allgrandchildren named egg in all children namedspam.
*Selects all child elements. For example, */eggselects all grandchildren named egg.
.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, .//egg selectsall egg elements in the entire tree.
..Selects the parent element. Returns None if thepath attempts to reach the ancestors of the startelement (the element find was called on).
[@attrib]Selects all elements that have the given attribute.
[@attrib='value']Selects all elements for which the given attributehas the given value. The value cannot containquotes.
[tag]Selects all elements that have a child namedtag. Only immediate children are supported.
[tag='text']Selects all elements that have a child namedtag whose complete text content, includingdescendants, equals the given text.
[position]Selects all elements that are located at the givenposition. The position can be either an integer(1 is the first position), the expression last()(for the last position), or a position relative tothe last position (e.g. last()-1).

Predicates (expressions within square brackets) must be preceded by a tagname, an asterisk, or another predicate. position predicates must bepreceded by a tag name.

20.5.3. Reference

20.5.3.1. Functions

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. An ElementTree willonly contain comment nodes if they have been inserted into tothe tree using one of the Element 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.

xml.etree.ElementTree.fromstring(text)

Parses an XML section from a string constant. Same as XML(). textis a string containing XML data. Returns an Element 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 XMLParserparser is used. Returns an Element instance.

New in version 3.2.

xml.etree.ElementTree.iselement(element)

Checks if an object appears to be a valid element object. element is anelement instance. Returns a true value 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 or file objectcontaining XML data. events is a sequence of events to report back. Thesupported events are the strings "start", "end", "start-ns" and"end-ns" (the “ns” events are used to get detailed namespaceinformation). If events 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 default TreeBuilder as atarget. Returns an iterator providing (event, elem) pairs.

Note that while iterparse() builds the tree incrementally, it issuesblocking reads on source (or the file it names). As such, it’s unsuitablefor applications where blocking reads can’t be made. For fully non-blockingparsing, see XMLPullParser.

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: The parser argument.

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 comment 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.

New 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", *, 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). Use encoding="unicode" togenerate a Unicode string (otherwise, a bytestring is generated). methodis either "xml", "html" or "text" (default is "xml").short_empty_elements has the same meaning as in ElementTree.write().Returns an (optionally) encoded string containing the XML data.

New in version 3.4: The short_empty_elements parameter.

xml.etree.ElementTree.tostringlist(element, encoding="us-ascii", method="xml", *, 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). Use encoding="unicode" togenerate a Unicode string (otherwise, a bytestring is generated). methodis either "xml", "html" or "text" (default is "xml").short_empty_elements has the same meaning as in ElementTree.write().Returns a list of (optionally) encoded strings containing the XML data.It does not guarantee any specific sequence, except thatb"".join(tostringlist(element)) == tostring(element).

New in version 3.2.

New in version 3.4: The short_empty_elements parameter.

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 standardXMLParser parser is used. Returns an Element 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 standardXMLParser parser is used. Returns a tuple containing anElement instance and a dictionary.

20.5.3.2. Element Objects

class xml.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, the text attribute holds either the text betweenthe element’s start tag and its first child or end tag, or None, andthe tail attribute holds either the text between the element’send tag and the next tag, or None. For the XML data

<a><b>1<c>2<d/>3</c></b>4</a>

the a element has None for both text and tail attributes,the b element has text "1" and tail "4",the c element has text "2" and tail None,and the d element has text None and tail "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 named key.

Returns the attribute value, or default 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 attribute key on the element to value.

The following methods work on the element’s children (subelements).

append(subelement)

Adds the element subelement to the end of this element’s internal listof subelements. Raises TypeError if subelement is not anElement.

extend(subelements)

Appends subelements from a sequence object with zero or more elements.Raises TypeError if a subelement is not an Element.

New in version 3.2.

find(match, namespaces=None)

Finds the first subelement matching match. match may be a tag nameor a path. Returns an element instanceor None. namespaces is an optional mapping from namespace prefixto full name.

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.

findtext(match, default=None, namespaces=None)

Finds text for the first subelement matching match. match may bea tag name or a path. Returns the text contentof the first matching element, or default 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.

getchildren()

Deprecated since version 3.2: Use list(elem) or iteration.

getiterator(tag=None)

Deprecated since version 3.2: Use method Element.iter() instead.

insert(index, subelement)

Inserts subelement at the given position in this element. RaisesTypeError if subelement is not an Element.

iter(tag=None)

Creates a tree iterator with the current element as the root.The iterator iterates over this element and all elements below it, indocument (depth first) order. If tag is not None or '*', onlyelements whose tag equals tag are returned from the iterator. If thetree structure is modified during iteration, the result is undefined.

New 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.

New 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.

New 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)

Removes subelement 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. This behaviorwill change in future versions. Use specific len(elem) or elem isNone test instead.

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")

20.5.3.3. ElementTree Objects

class xml.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 XML file 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.

getiterator(tag=None)

Deprecated since version 3.2: Use method ElementTree.iter() instead.

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.

New in version 3.2.

parse(source, parser=None)

Loads an external XML section into this element tree. source is a filename or file 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, Nonefor only if not US-ASCII or UTF-8 or Unicode (default is None).default_namespace sets the default XML namespace (for “xmlns”).method is either "xml", "html" or "text" (default is"xml").The keyword-only short_empty_elements parameter controls the formattingof elements that contain no content. If True (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 the encoding argument. If encoding is"unicode", the output is a string; otherwise, it’s binary. Note thatthis may conflict with the type of file if it’s an openfile object; make sure you do not try to write a string to abinary stream and vice versa.

New in version 3.4: The short_empty_elements parameter.

This is the XML file that is going to be manipulated:

<html> <head> <title>Example page</title> </head> <body> <p>Moved to <a href="http://example.org/">example.org</a> or <a href="http://example.com/">example.com</a>.</p> </body></html>

Example of changing the attribute “target” of every link in first paragraph:

>>> from xml.etree.ElementTree import ElementTree>>> tree = ElementTree()>>> tree.parse("index.xhtml")<Element 'html' at 0xb77e6fac>>>> p = tree.find("body/p") # Finds first occurrence of tag p in body>>> p<Element 'p' at 0xb77ec26c>>>> links = list(p.iter("a")) # Returns list of all links>>> links[<Element 'a' at 0xb77ec2ac>, <Element 'a' at 0xb77ec1cc>]>>> for i in links: # Iterates through all found links...  i.attrib["target"] = "blank">>> tree.write("output.xhtml")

20.5.3.4. QName Objects

class xml.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. If tag is given, the first argument isinterpreted as a URI, and this argument is interpreted as a local name.QName instances are opaque.

20.5.3.5. TreeBuilder Objects

class xml.etree.ElementTree.TreeBuilder(element_factory=None)

Generic element structure builder. This builder converts a sequence ofstart, data, and end method calls to a well-formed element structure. Youcan use this class to build an element structure using a custom XML parser,or a parser for some other XML-like format. element_factory, when given,must be a callable accepting two positional arguments: a tag anda dict of attributes. It is expected to return a new element instance.

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.

In addition, a custom TreeBuilder object can provide thefollowing method:

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.

New in version 3.2.

20.5.3.6. XMLParser Objects

class xml.etree.ElementTree.XMLParser(html=0, target=None, encoding=None)

This class is the low-level building block of the module. It usesxml.parsers.expat for efficient, event-based parsing of XML. It canbe fed XML data incrementally with the feed() method, and parsingevents are translated to a push API - by invoking callbacks on the targetobject. If target is omitted, the standard TreeBuilder is used.The html argument was historically used for backwards compatibility and isnow deprecated. If encoding [1] is given, the value overrides theencoding specified in the XML file.

Deprecated since version 3.4: The html argument. The remaining arguments should be passed viakeyword to prepare for the removal of the html argument.

close()

Finishes feeding data to the parser. Returns the result of calling theclose() method of the target passed during construction; by default,this is the toplevel document element.

doctype(name, pubid, system)

Deprecated since version 3.2: Define the TreeBuilder.doctype() method on a custom TreeBuildertarget.

feed(data)

Feeds data to the parser. data is encoded data.

XMLParser.feed() calls target’s start(tag, attrs_dict) methodfor each opening tag, its end(tag) method for each closing tag, and datais processed by method data(data). XMLParser.close() callstarget’s method close(). XMLParser can be used not only forbuilding a tree structure. This is an example of counting the maximum depthof an XML file:

>>> from xml.etree.ElementTree import XMLParser>>> 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 > 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...>>> target = MaxDepth()>>> parser = XMLParser(target=target)>>> exampleXml = """... <a>...  <b>...  </b>...  <b>...  <c>...  <d>...  </d>...  </c>...  </b>... </a>""">>> parser.feed(exampleXml)>>> parser.close()4

20.5.3.7. XMLPullParser Objects

class xml.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","start-ns" and "end-ns" (the “ns” events are used to get detailednamespace information). If events is omitted, only "end" events arereported.

feed(data)

Feed the given bytes data to the parser.

close()

Signal the parser that the data stream is terminated. UnlikeXMLParser.close(), this method always returns None.Any events not yet retrieved when the parser is closed can still beread with read_events().

read_events()

Return an iterator over the events which have been encountered in thedata fed to theparser. The iterator yields (event, elem) pairs, where event is astring representing the type of event (e.g. "end") and elem is theencountered Element object.

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 from read_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.

New in version 3.4.

20.5.3.8. Exceptions

class xml.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 ofxml.parsers.expat for the list of error codes and their meanings.

position

A tuple of line, 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. See https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecland https://www.iana.org/assignments/character-sets/character-sets.xhtml.

Navigation

  • index
  • modules |
  • next |
  • previous |
  • 20.5. xml.etree.ElementTree — The ElementTree XML API (2)
  • Python »
  • 3.6.3 Documentation »
  • The Python Standard Library »
  • 20. Structured Markup Processing Tools »

© Copyright 2001-2017, Python Software Foundation.
The Python Software Foundation is a non-profit corporation.Please donate.
Last updated on Oct 03, 2017.Found a bug?
Created using Sphinx 1.6.3.

previous page start next page

20.5. xml.etree.ElementTree — The ElementTree XML API (2024)
Top Articles
Dead Space 2023 is feeling scarier than ever while staying true to the original
Dead Space Remake Trainer
Tj Nails Victoria Tx
Nwi Police Blotter
Kansas Craigslist Free Stuff
Bluegabe Girlfriend
Infinite Campus Parent Portal Hall County
Nichole Monskey
Jscc Jweb
Simon Montefiore artikelen kopen? Alle artikelen online
Vcuapi
Learn2Serve Tabc Answers
Aucklanders brace for gales, hail, cold temperatures, possible blackouts; snow falls in Chch
Po Box 35691 Canton Oh
Mals Crazy Crab
Parentvue Clarkston
Energy Healing Conference Utah
Caledonia - a simple love song to Scotland
Loft Stores Near Me
Wgu Academy Phone Number
Melissababy
Greenville Sc Greyhound
Filthy Rich Boys (Rich Boys Of Burberry Prep #1) - C.M. Stunich [PDF] | Online Book Share
Sister Souljah Net Worth
Inter Miami Vs Fc Dallas Total Sportek
Free T33N Leaks
Schooology Fcps
Jail Roster Independence Ks
Google Flights To Orlando
Devotion Showtimes Near The Grand 16 - Pier Park
Spy School Secrets - Canada's History
Newcardapply Com 21961
Ma Scratch Tickets Codes
Hotels Near New Life Plastic Surgery
Ljw Obits
Eleceed Mangaowl
Jail View Sumter
Husker Football
Emily Tosta Butt
Www.craigslist.com Waco
Tunica Inmate Roster Release
Academic Notice and Subject to Dismissal
Dicks Mear Me
Canonnier Beachcomber Golf Resort & Spa (Pointe aux Canonniers): Alle Infos zum Hotel
All Buttons In Blox Fruits
4Chan Zelda Totk
The Latest Books, Reports, Videos, and Audiobooks - O'Reilly Media
Treatise On Jewelcrafting
Sleep Outfitters Springhurst
Craigslist Cars And Trucks For Sale By Owner Indianapolis
Laurel Hubbard’s Olympic dream dies under the world’s gaze
Latest Posts
Article information

Author: Rueben Jacobs

Last Updated:

Views: 5775

Rating: 4.7 / 5 (57 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Rueben Jacobs

Birthday: 1999-03-14

Address: 951 Caterina Walk, Schambergerside, CA 67667-0896

Phone: +6881806848632

Job: Internal Education Planner

Hobby: Candle making, Cabaret, Poi, Gambling, Rock climbing, Wood carving, Computer programming

Introduction: My name is Rueben Jacobs, I am a cooperative, beautiful, kind, comfortable, glamorous, open, magnificent person who loves writing and wants to share my knowledge and understanding with you.