Data formats: XML, INI, TOML and pickle · 2 / 15 Theory

Reading XML with ElementTree

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.tag is the tag, e.text the text, e.attrib the dictionary of attributes and e.get("x") one attribute.
  • Iterating over an element gives its direct children; e.iter("tag") searches the whole subtree.
  • find returns the first matching element (or None); findall, all of them; findtext, its text directly. They accept paths with / and filters such as [@id='2'].
  • If the XML is malformed, ET.ParseError is raised.

You practice it in Total of an order in XML, Count XML tags and Depth of an XML tree.