Read an XML File with xml.etree.ElementTree in Python
Parse an XML file and print its root and child elements using the standard library's xml.etree.ElementTree module.
Python code
25 linesimport xml.etree.ElementTree as ET
def read_xml_file(file_path):
"""Read an XML file and print its structure."""
tree = ET.parse(file_path)
root = tree.getroot()
print(f"Root element: {root.tag}")
for child in root:
print(f"Child element: {child.tag}, text: {child.text}")
if __name__ == "__main__":
# Create a sample XML file for demonstration
sample_xml = """<?xml version=\"1.0\"?>
<library>
<book>Python Basics</book>
<book>Data Science</book>
<book>Web Development</book>
</library>
"""
with open("sample.xml", "w") as f:
f.write(sample_xml)
read_xml_file("sample.xml")
Output
Root element: library
Child element: book, text: Python Basics
Child element: book, text: Data Science
Child element: book, text: Web Development
How it works
The ET.parse function reads the XML file and returns an ElementTree object. Calling getroot() gives the top-level element, and iterating over root visits each direct child. Each element's tag attribute holds the element name and text contains the inner text content. This approach works for well-formed XML files and is memory-efficient for small to medium documents.
Common mistakes
- Forgetting to import xml.etree.ElementTree as ET
- Assuming `ET.parse` returns the root directly instead of a tree object
- Trying to access child text via `child.text` without checking for None
Variations
- Use `ET.fromstring` to parse an XML string instead of a file.
- Use `root.iter('book')` to find all descendant elements with a specific tag.
Real-world use cases
- Reading configuration files stored in XML format for application settings.
- Parsing RSS feeds or sitemap XML responses from web services.
- Extracting data from legacy systems that export XML data files for analysis.
Sponsored
More from Files & data
- Append a Line to a Log File in Python easy
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
Keep learning
Related tutorials and quizzes for this topic.