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.

Easy Python 3.9+ Aug 9, 2026 Files & data 13 views 0 copies

Python code

25 lines
Python 3.9+
import 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

stdout
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

  1. Use `ET.fromstring` to parse an XML string instead of a file.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.