XML represents data as a tree of elements. Each element has a tag, optional attributes, text and other child elements. ElementTree turns it into objects that you walk like lists.
import xml.etree.ElementTree as ET
text = """<library>
<book id="1" year="1605"><title>Quixote</title><author>Cervantes</author></book>
<book id="2" year="1967"><title>One Hundred Years</title><author>Garcia Marquez</author></book>
</library>"""
root = ET.fromstring(text)
print(root.tag, len(root)) # library 2
for book in root: # direct children
print(book.get("id"), book.find("title").text, book.attrib["year"])
# 1 Quixote 1605
# 2 One Hundred Years 1967
print([a.text for a in root.iter("author")]) # ['Cervantes', 'Garcia Marquez']
print(root.find("book[@id='2']/title").text) # One Hundred Years
print(root.findtext("book/author")) # Cervantes (the first one)
print(root.find("magazine")) # None: does not exist
ET.fromstring(text)parses a text;ET.parse("file.xml").getroot()does it from a file. They return the root element.e.tagis the tag,e.textthe text,e.attribthe dictionary of attributes ande.get("x")one attribute.- Iterating over an element gives its direct children;
e.iter("tag")searches the whole subtree. findreturns the first matching element (orNone);findall, all of them;findtext, its text directly. They accept paths with/and filters such as[@id='2'].- If the XML is malformed,
ET.ParseErroris raised.
You practice it in Total of an order in XML, Count XML tags and Depth of an XML tree.