elementtree list in xml in python

Here is an example of how to parse an XML file using ElementTree and retrieve a list of elements with a specific tag:

import xml.etree.ElementTree as ET

# parse xml file
tree = ET.parse('example.xml')

# get root element
root = tree.getroot()

# define tag to search for
tag = 'example_tag'

# create empty list to store elements
elements = []

# iterate over all elements in tree
for elem in root.iter():
    # check if element has the desired tag
    if elem.tag == tag:
        # append element to list

# print list of elements with desired tag
478 chars
24 lines

This code uses ElementTree's iter() method to traverse through the XML tree and search for elements with the desired tag. When an element is found with the desired tag, it is appended to the elements list. Once all elements have been searched, the list of elements is printed.

gistlibby LogSnag