How to Parse XML with ElementTree

We'll cover the following...

Now we get to learn how to do some basic parsing with ElementTree. First we’ll read through the code and then we’ll go through bit by bit so we can understand it. Note that this code is based around the original example, but it should work on the second one as well.

Press + to interact
import xml.etree.cElementTree as ET
def parseXML(xml_file):
"""
Parse XML with ElementTree
"""
tree = ET.ElementTree(file=xml_file)
print(tree.getroot())
root = tree.getroot()
print("tag=%s, attrib=%s" % (root.tag, root.attrib))
for child in root:
print(child.tag, child.attrib)
if child.tag == "appointment":
for step_child in child:
print(step_child.tag)
# iterate over the entire tree
print("-" * 40)
print("Iterating using a tree iterator")
print("-" * 40)
iter_ = tree.getiterator()
for elem in iter_:
print(elem.tag)
# get the information via the children!
print("-" * 40)
print("Iterating using getchildren()")
print("-" * 40)
appointments = root.getchildren()
for appointment in appointments:
appt_children = appointment.getchildren()
for appt_child in appt_children:
print("%s=%s" % (appt_child.tag, appt_child.text))
if __name__ == "__main__":
parseXML("appt.xml")

You may have already noticed this, but in this example and the last one, we’ve been importing cElementTree instead of the normal ElementTree. The main ...