Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 2acc525

Browse files
committed
Issue #17011: Fix caching of xpath path when namespaces are present.
Thanks to Stefan Behnel for the report and proposed solution & test.
1 parent 3ceaff0 commit 2acc525

2 files changed

Lines changed: 18 additions & 2 deletions

File tree

Lib/test/test_xml_etree.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1679,6 +1679,20 @@ def test_test_find_with_ns(self):
16791679
summarize_list(e.findall(".//{http://effbot.org/ns}tag")),
16801680
['{http://effbot.org/ns}tag'] * 3)
16811681

1682+
def test_findall_different_nsmaps(self):
1683+
root = ET.XML('''
1684+
<a xmlns:x="X" xmlns:y="Y">
1685+
<x:b><c/></x:b>
1686+
<b/>
1687+
<c><x:b/><b/></c><y:b/>
1688+
</a>''')
1689+
nsmap = {'xx': 'X'}
1690+
self.assertEqual(len(root.findall(".//xx:b", namespaces=nsmap)), 2)
1691+
self.assertEqual(len(root.findall(".//b", namespaces=nsmap)), 2)
1692+
nsmap = {'xx': 'Y'}
1693+
self.assertEqual(len(root.findall(".//xx:b", namespaces=nsmap)), 1)
1694+
self.assertEqual(len(root.findall(".//b", namespaces=nsmap)), 2)
1695+
16821696
def test_bad_find(self):
16831697
e = ET.XML(SAMPLE_XML)
16841698
with self.assertRaisesRegex(SyntaxError, 'cannot use absolute path'):

Lib/xml/etree/ElementPath.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -246,10 +246,12 @@ def __init__(self, root):
246246

247247
def iterfind(elem, path, namespaces=None):
248248
# compile selector pattern
249+
cache_key = (path, None if namespaces is None
250+
else tuple(sorted(namespaces.items())))
249251
if path[-1:] == "/":
250252
path = path + "*" # implicit all (FIXME: keep this?)
251253
try:
252-
selector = _cache[path]
254+
selector = _cache[cache_key]
253255
except KeyError:
254256
if len(_cache) > 100:
255257
_cache.clear()
@@ -269,7 +271,7 @@ def iterfind(elem, path, namespaces=None):
269271
token = next()
270272
except StopIteration:
271273
break
272-
_cache[path] = selector
274+
_cache[cache_key] = selector
273275
# execute selector pattern
274276
result = [elem]
275277
context = _SelectorContext(elem)

0 commit comments

Comments
 (0)