Use ElementTree.findall for direct child records
Also published in our Blogger archive.
Use ElementTree.findall for direct child records
Use root.findall("record") when the records you want are immediate children of the current element. It does not recursively descend into nested containers. That makes the selection match a document structure where the root catalogue owns top-level records and a section may contain records with a different role.
The synthetic input contains two direct <record> children of <catalog> and one nested <record> inside <section>. The first findall() call returns only identifiers A and B. For contrast, .findall(".//record") uses the supported // XPath form to select records at every depth, producing A, nested, and B. The assertions prove the difference for this particular tree, while the exact output makes the choice visible.
This is ElementTree’s limited XPath support rather than a full XPath engine. Namespaced XML needs qualified names or a namespace mapping; a bare "record" will not match a namespaced tag. Also, direct-child selection is correct only if the XML schema really defines the desired records at that level. It is not validation that all records have identifiers or that the overall document is well-formed beyond successful parsing. findall() and these path forms are available in all currently supported Python versions.
AI assistance disclosure: this article was drafted with AI assistance and should be aligned with the document’s actual namespaces and hierarchy.
Source: Python ElementTree documentation.
import xml.etree.ElementTree as ET
root = ET.fromstring(
"<catalog>"
'<record id="A" />'
'<section><record id="nested" /></section>'
'<record id="B" />'
"</catalog>"
)
direct_ids = [record.get("id") for record in root.findall("record")]
all_ids = [record.get("id") for record in root.findall(".//record")]
assert direct_ids == ["A", "B"]
assert all_ids == ["A", "nested", "B"]
print("direct=" + ",".join(direct_ids))
print("recursive=" + ",".join(all_ids))
direct=A,B
recursive=A,nested,B