[utils] find_xpath_attr: Support quotes in attribute values (#17857)

Authored by: doe1080
This commit is contained in:
doe1080
2026-11-22 21:12:00 +00:00
committed by GitHub
parent 4b91f5d702
commit 1507b26936
2 changed files with 12 additions and 3 deletions
+3
View File
@@ -527,6 +527,7 @@ class TestUtil(unittest.TestCase):
<node x="a" y="c" />
<node x="b" y="d" />
<node x="" />
<node x="a'b&quot;c" y="1" />
</root>'''
doc = compat_etree_fromstring(testxml)
@@ -541,6 +542,8 @@ class TestUtil(unittest.TestCase):
self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'c'), doc[2])
self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'd'), doc[3])
self.assertEqual(find_xpath_attr(doc, './/node', 'x', ''), doc[4])
self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'a\'b"c'), doc[5])
self.assertEqual(find_xpath_attr(doc, './/node', 'y', 1), doc[5])
def test_xpath_with_ns(self):
testxml = '''<root xmlns:media="http://example.com/">
+9 -3
View File
@@ -234,9 +234,15 @@ def partial_application(func):
def find_xpath_attr(node, xpath, key, val=None):
""" Find the xpath xpath[@key=val] """
assert re.match(r'^[a-zA-Z_-]+$', key)
expr = xpath + (f'[@{key}]' if val is None else f"[@{key}='{val}']")
return node.find(expr)
assert re.fullmatch(r'[a-zA-Z_-]+', key)
expr = f'{xpath}[@{key}]'
if val is None:
return node.find(expr)
val = str(val)
for n in node.iterfind(expr):
if n.get(key) == val:
return n
def xpath_with_ns(path, ns_map):