Skip to content

Commit 76642af

Browse files
xml.etree: Fix namespace prefix resolution in ElementPath xpath_tokenizer (GH-140123)
The namespace prefix resolution in ElementPath.xpath_tokenizer now properly uses globally registered namespaces after trying local namespaces first. This ensures consistent namespace handling across both Python and C implementations.
1 parent f852ac1 commit 76642af

File tree

2 files changed

+10
-4
lines changed

2 files changed

+10
-4
lines changed

Lib/xml/etree/ElementPath.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
#
1919
2020
# http://www.pythonware.com
21+
22+
from . import ElementTree
2123
#
2224
# --------------------------------------------------------------------
2325
# The ElementTree toolkit is
@@ -79,11 +81,14 @@ def xpath_tokenizer(pattern, namespaces=None):
7981
if tag and tag[0] != "{":
8082
if ":" in tag:
8183
prefix, uri = tag.split(":", 1)
82-
try:
83-
if not namespaces:
84-
raise KeyError
84+
if namespaces and prefix in namespaces:
85+
# Use the passed-in namespace map first
8586
yield ttype, "{%s}%s" % (namespaces[prefix], uri)
86-
except KeyError:
87+
elif prefix in ElementTree._namespace_map:
88+
# Then check the global registry
89+
yield ttype, "{%s}%s" % (ElementTree._namespace_map[prefix], uri)
90+
else:
91+
# No namespace found, raise error
8792
raise SyntaxError("prefix %r not found in prefix map" % prefix) from None
8893
elif default_namespace and not parsing_attribute:
8994
yield ttype, "{%s}%s" % (default_namespace, tag)
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
ElementTree.find() and similar methods now properly use globally registered namespaces when resolving namespace prefixes in XPath expressions.

0 commit comments

Comments
 (0)