Python ElementTree XML Namespaces: Why find() Returns None
Fix ElementTree namespace queries with expanded names, query aliases and correct paths. Run a 624-check Python lab covering attributes, empty elements and prefix changes.
If an XML element belongs to a default namespace, ElementTree stores its tag as {URI}local-name. find("item") searches for an unqualified name and can return None. Use an expanded name or a query namespace mapping, verify the path relative to the current node, and check the result with is None. Unprefixed attributes do not inherit the default namespace.
Start with the name that Python actually parsed
An XML export can contain an item element that is plainly visible in an editor while root.find("item") returns None. Before changing parsers, print repr(root.tag), then print repr(child.tag) and child.attrib for each direct child. That small inspection separates a name mismatch from a path mismatch. In a default namespace, the parsed name might be {urn:prepwithproof:catalog:v1}item. Searching for item asks for a different name.
This guide uses an invented catalog with a second metadata vocabulary and a legacy section that deliberately has no namespace. These collisions make a useful debugging fixture: a query should select the catalog item without accidentally accepting a metadata item or a legacy item. The complete lab below runs locally with the Python standard library and needs no downloads, credentials or network connection.
Treat the fixture as trusted input. Namespace-aware selection is a data interpretation technique, not a defense against malicious XML or a replacement for schema validation. For externally supplied documents, review the Python XML security guidance separately and decide input limits and parser policy before adopting any parsing example.
Separate vocabulary identity from document spelling
ElementTree represents a qualified element name as {namespace URI}local-name. A prefix such as cat is a document-level spelling for that URI. The lab queries through c even when the source uses a default namespace or p17. The application chooses its query aliases; they need not copy the source aliases. These rules follow the ElementTree namespace documentation and the W3C namespace specification.
For an importer, this suggests a concrete contract: accept the catalog vocabulary URI and expected root name, then extract only the children belonging to that vocabulary. Keep the URI in one constant. If a supplier changes only its prefixes, the importer should continue working. If it changes the URI, decide explicitly whether the new vocabulary is compatible before accepting it.
A namespace URI is an identifier here. Do not add a network request merely to resolve it. Nor should a repair routine casually lowercase the URI, append a slash, or remove a version suffix. In the fixture, adding a slash produces a different expanded name and the extractor rejects the root. That deliberate failure is more informative than returning an empty successful import.
| Input spelling | Parsed name or key | How the lab selects it |
|---|---|---|
| item under the catalog default namespace | {urn:prepwithproof:catalog:v1}item | c:item with NS |
| meta:item | {urn:prepwithproof:metadata:v1}item | m:item with NS |
| id="A1" | id attribute | item.get("id") |
| meta:id="source-7" | {urn:prepwithproof:metadata:v1}id attribute | item.get(expanded attribute name) |
| item inside xmlns="" | item without namespace | plain/item |
Source: Python 3.12: ElementTree namespace parsing and search APIs ↗
Choose a query style that exposes the intended contract
For a single element, an expanded name is direct and easy to log: root.find(f"{{{CAT}}}item"). For several paths, a namespace dictionary keeps them readable: NS = {"c": CAT, "m": META}, followed by root.find("c:item/c:title", NS). Keep that mapping beside the extractor so a reviewer can connect every alias to the intended vocabulary.
ElementTree also accepts an empty-prefix mapping, such as {"": CAT}, to qualify unprefixed element names in a search expression. The lab checks that root.find("item", {"": CAT}) selects the same child. This can suit a document containing one vocabulary. Explicit aliases are easier to review in the mixed catalog because a plain-looking query would otherwise conceal which namespace it intends.
Do not make a namespace mismatch disappear by stripping everything before the closing brace from every parsed tag. In this fixture that would collapse three meanings of item into one local name. An importer might silently ingest audit metadata as catalog content. If several vocabulary versions are supported, write a small allowlist and a deliberate extraction branch for each accepted version instead.
Source: Python 3.12: ElementTree namespace parsing and search APIs ↗
A correct namespace does not fix an incorrect path
The starting node matters. After parsing this fixture, root already is the catalog element. Searching c:catalog/c:item asks for another catalog child beneath it and therefore finds nothing. Searching c:item selects the intended direct child. Searching c:title from the root also fails because title is one level deeper; c:item/c:title reaches it.
A descendant search such as .//c:title can help inspect an unfamiliar document, but broadening every query to descendants changes the contract. An embedded recommendation, attachment or historical record might contain another title with the same vocabulary name. For a production importer, begin with the expected structural path and report when it is absent. Broaden the search only when that broader structure is intentional.
The ElementTree namespace wildcard pattern {*}item deliberately ignores the namespace part of the name. In the lab, root.findall("{*}item") returns two direct children from different vocabularies, while .//{*}item returns three including the legacy descendant. That is useful for diagnosis and intentionally too broad for the catalog extractor. A local-name match alone does not establish business meaning.
Inspect attributes independently of the element namespace
The catalog item has both id="A1" and meta:id="source-7". Its unprefixed id attribute has no namespace even though its element belongs to the default namespace. Accordingly, item.get("id") returns A1, while asking for {catalog-URI}id returns None. The metadata attribute uses its own expanded name and returns source-7. This distinction is specified by W3C namespace defaulting.
When debugging an unexpected missing identifier, print the attribute dictionary rather than assuming every field shares the element namespace. Decide whether the application requires the local business identifier, the source metadata identifier or both. The extractor returns them in different tuple positions so an accidental swap is visible in the expected output.
Namespace declarations and data attributes serve different purposes. Avoid treating an xmlns declaration as a record field or expecting the ordinary attribute dictionary to provide a ready-made query mapping. For this fixed vocabulary contract, the application already knows the accepted namespace URIs and can define its own mapping without recovering the source spelling.
Use an explicit missing-node check
Write if title is None when the question is whether a search found an element. Do not use a generic truthiness check as a substitute. A title with no child elements is still a found element; its text may nevertheless be absent. That leaves separate decisions for missing nodes, empty content and content containing only whitespace.
The empty-title fixture demonstrates two useful observations. Its title element exists and has text equal to None. findtext returns an empty string for that existing empty element, while the supplied default MISSING is returned for an absent child. An application that requires a nonblank title should validate the extracted text separately, with an explicit policy for whitespace and allowed characters.
The main extractor rejects a missing catalog title but intentionally does not implement a complete catalog schema. It does not enforce unique identifiers, minimum title length or any business rule beyond the demonstrated root and child selection. Add those checks where your actual data contract requires them, keeping namespace failures distinguishable from content validation failures.
Run the complete mixed-namespace lab
Save the following as xml_namespaces_lab.py and run python xml_namespaces_lab.py on Python 3.12. The fixture is generated in memory. The check function counts assertions without relying on a testing package; the prefix loop creates 200 equivalent source spellings and compares extraction against a fixed expected record.
The published code was executed on Python 3.12.14 and passed 624 checks. Those checks cover the default namespace, application-chosen aliases, qualified and unqualified attributes, structural paths, namespace wildcards, an empty element, a changed URI and a serialization round trip. This is a controlled local example, not a test of supplier documents, streaming memory behavior, schema conformance or hostile inputs.
import sys
import xml.etree.ElementTree as ET
CAT = 'urn:prepwithproof:catalog:v1'
META = 'urn:prepwithproof:metadata:v1'
NS = {'c': CAT, 'm': META}
checks = 0
def check(condition):
global checks
assert condition
checks += 1
def fixture(prefix=None):
# Trusted, invented local XML; no network or user input.
q = '' if prefix is None else prefix + ':'
declaration = 'xmlns' if prefix is None else 'xmlns:' + prefix
return f'''<{q}catalog {declaration}="{CAT}" xmlns:meta="{META}">
<{q}item id="A1" meta:id="source-7">
<{q}title>Cloud Notes</{q}title>
</{q}item>
<meta:item id="audit"><meta:title>Audit Notes</meta:title></meta:item>
<plain xmlns=""><item id="legacy"><title>Legacy Notes</title></item></plain>
</{q}catalog>'''
def extract(root):
if root.tag != f'{{{CAT}}}catalog':
raise ValueError('Unexpected catalog namespace or root')
rows = []
for item in root.findall('c:item', NS):
title = item.find('c:title', NS)
if title is None:
raise ValueError('Missing catalog title')
rows.append((item.get('id'), item.get(f'{{{META}}}id'), title.text))
return rows
root = ET.fromstring(fixture())
check(root.find('item') is None)
item = root.find('c:item', NS)
check(item is not None)
check(item.tag == f'{{{CAT}}}item')
check(item.get('id') == 'A1')
check(item.get(f'{{{CAT}}}id') is None)
check(item.get(f'{{{META}}}id') == 'source-7')
check(root.find(f'{{{CAT}}}item') is item)
check(root.find('item', {'': CAT}) is item)
check(root.find('chosen:item', {'chosen': CAT}) is item)
check(root.find('c:catalog/c:item', NS) is None)
check(root.find('c:item/c:title', NS).text == 'Cloud Notes')
check(root.find('c:title', NS) is None)
check(root.find('.//c:title', NS).text == 'Cloud Notes')
check(root.find('plain/item/title').text == 'Legacy Notes')
check(len(root.findall('{*}item')) == 2)
check(len(root.findall('.//{*}item')) == 3)
check(extract(root) == [('A1', 'source-7', 'Cloud Notes')])
# Lexical prefix changes must not change extracted business data.
for n in range(200):
alternate = ET.fromstring(fixture('p' + str(n)))
check(alternate.tag == root.tag)
check(extract(alternate) == [('A1', 'source-7', 'Cloud Notes')])
check(alternate.find('c:item', NS).get('id') == 'A1')
# A namespace URI change is a contract change, not a prefix rename.
wrong = ET.fromstring(fixture().replace(CAT, CAT + '/'))
check(wrong.find('c:item', NS) is None)
try:
extract(wrong)
except ValueError:
check(True)
else:
raise AssertionError('Wrong root accepted')
# Distinguish missing nodes, existing empty nodes and whitespace text.
empty = ET.fromstring(f'<catalog xmlns="{CAT}"><item><title/></item></catalog>')
title = empty.find('c:item/c:title', NS)
check(title is not None)
check(title.text is None)
check(empty.findtext('c:item/c:title', default='MISSING', namespaces=NS) == '')
check(empty.findtext('c:item/c:absent', default='MISSING', namespaces=NS) == 'MISSING')
# Serialization may choose other prefixes; expanded-name queries still work.
roundtrip = ET.fromstring(ET.tostring(root))
check(extract(roundtrip) == extract(root))
print(f'PASS: {checks} checks; Python {sys.version.split()[0]}')
Check semantic results after serialization
The final assertion serializes the tree and parses it again before comparing extracted records. It does not compare XML strings. A serializer can choose a different prefix spelling while preserving the expanded element and attribute names that this extractor uses. If your downstream system needs particular output conventions, test that separate output contract explicitly.
This round trip checks only the selected catalog data. It makes no promise of byte-for-byte preservation, original formatting, original declaration placement or a complete XML document fidelity model. In particular, the example does not interpret prefixes that might occur inside attribute values. Such values are ordinary text unless the vocabulary gives them additional meaning; blindly renaming text would need a different design.
Turn a None result into a specific diagnosis
Work through one failing record in this order: inspect the parsed root and direct child names; compare the accepted URI; verify the path relative to the current node; inspect attribute keys; then separate a missing element from empty text. Capture a small redacted sample that reproduces the failure and preserve it as a regression fixture.
Once the intended selection is correct, compare the extracted business data with an independent expected record. Include a second vocabulary with the same local names and a renamed-prefix variant, as this lab does. That pair catches two opposite mistakes: accepting unrelated elements and rejecting equivalent source spelling. It gives future maintainers a precise reason for retaining namespace-aware queries.
An XML namespace problem becomes manageable when the importer names its vocabulary contract explicitly. Keep expanded-name identity, structural location and content validation as separate checks. Then a None result is a useful signal about a particular mismatch, and a harmless source prefix change stops looking like a data format migration.
Your next steps
- Match the namespace URI and local name, not the lexical prefix used by the source.
- Check direct-child paths before widening a query to all descendants.
- Read qualified and unqualified attributes using their actual parsed keys.
- Keep missing elements, empty text and business validation separate.
Sources & official resources
Linked resources checked on 2026-11-03. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →