Python Language Manipulating XML Opening and reading using an ElementTree

30% OFF - 9th Anniversary discount on Entity Framework Extensions until December 15 with code: ZZZANNIVERSARY9

Example

Import the ElementTree object, open the relevant .xml file and get the root tag:

import xml.etree.ElementTree as ET
tree = ET.parse("yourXMLfile.xml")
root = tree.getroot()

There are a few ways to search through the tree. First is by iteration:

for child in root:
    print(child.tag, child.attrib)

Otherwise you can reference specific locations like a list:

print(root[0][1].text)

To search for specific tags by name, use the .find or .findall:

print(root.findall("myTag"))
print(root[0].find("myOtherTag"))


Got any Python Language Question?