Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk3 min

How to Read XML Files in Python with ElementTree

Use Python’s built-in ElementTree to parse an XML file, navigate its elements, and extract values. Learn when to use fromstring, iterparse, and XMLPullParser.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a regular XML file on disk, Python’s built-in xml.etree.ElementTree module is the simplest starting point: call ET.parse(), get the root element, then navigate its children. If the XML is already a string in memory, use ET.fromstring() instead.

Read an XML file with ElementTree

ET.parse() accepts a filename or a file object and returns an ElementTree. Call getroot() to access the document’s root element.

import xml.etree.ElementTree as ET

tree = ET.parse("data.xml")
root = tree.getroot()

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

Each parsed element represents a node in the XML hierarchy. Its tag is the element name, attrib contains its attributes, and child elements can be iterated over. An element’s text content is available through .text.

Extract elements, text, and attributes

Use find() to look for the first matching child and findall() to find matching direct children. Retrieve an attribute with .get() or inspect .attrib.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
for record in root.findall("record"):
    name = record.get("name")
    value_element = record.find("value")
    value = value_element.text if value_element is not None else None
    print(name, value)

The check for None is important: find() returns None when it cannot find a matching child. Use the actual element names and attributes in your document rather than assuming they are present.

Parse XML text already in memory

If your XML is held in a Python string rather than a file, pass it to fromstring(). Unlike parse(), this returns the root element directly.

import xml.etree.ElementTree as ET

xml_text = "<catalog><item>Book</item></catalog>"
root = ET.fromstring(xml_text)

item = root.find("item")
if item is not None:
    print(item.text)

Choose an API for larger or streamed XML

The right interface depends on where the input comes from and how you need to process it. Python documents several XML APIs; these are the main distinctions relevant to reading data:

Input or need Interface What to know
File path or file object; convenient tree navigation xml.etree.ElementTree.parse() Builds an element tree for navigation.
XML text already in memory xml.etree.ElementTree.fromstring() Returns the root element directly.
Large file processed with blocking reads ElementTree.iterparse() Processes parsing events as input is read, but parsed elements remain in the tree unless you clear or remove them.
Non-blocking input arriving in chunks XMLPullParser Feed data incrementally and retrieve parsing events without relying on a blocking read.
A different processing or programming interface is required xml.dom, xml.dom.minidom, xml.dom.pulldom, or xml.sax Python documents these DOM and SAX interfaces alongside ElementTree.

iterparse() incrementally builds the tree, but that does not by itself free processed elements. When processing records from a large document, clear them or remove processed children as appropriate. The right cleanup pattern depends on the XML structure and should be checked against the memory needs of the application.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Search XML that uses namespaces

Namespace declarations change how element names are matched. When searching with ElementTree, use the namespace URI declared by the document, either through a namespace mapping or in the expanded {namespace-uri}local-name form. Do not guess the URI: obtain it from the XML’s namespace declarations.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Handle untrusted XML and check Expat

If a file comes from an untrusted or unauthenticated source, a basic parsing example is not a complete security policy. Python’s XML security guidance describes risks to XML-processing systems including denial of service, local-file access, network connections, and firewall circumvention. It also notes that Expat itself does not access local files or create network connections by default.

Python’s documentation warns that Expat versions lower than 2.7.2 may be vulnerable to “billion laughs,” “quadratic blowup,” and “large tokens” attacks, or disproportionate dynamic-memory use. Python may use bundled or system-wide Expat depending on how the interpreter was configured. Check the version in the environment where the program runs:

import pyexpat

print(pyexpat.EXPAT_VERSION)

These security details are version-sensitive; consult the current Python XML vulnerabilities guidance for the target interpreter. Python’s XML overview separately flags decompression-bomb risk for xmlrpc; that warning should not be treated as a claim that every ordinary ElementTree file parse has the same issue.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Official Python references

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.