Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 1 | # |
| 2 | # ElementTree |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 3 | # $Id: ElementPath.py 3375 2008-02-13 08:05:08Z fredrik $ |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 4 | # |
| 5 | # limited xpath support for element trees |
| 6 | # |
| 7 | # history: |
| 8 | # 2003-05-23 fl created |
| 9 | # 2003-05-28 fl added support for // etc |
| 10 | # 2003-08-27 fl fixed parsing of periods in element names |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 11 | # 2007-09-10 fl new selection engine |
| 12 | # 2007-09-12 fl fixed parent selector |
| 13 | # 2007-09-13 fl added iterfind; changed findall to return a list |
| 14 | # 2007-11-30 fl added namespaces support |
| 15 | # 2009-10-30 fl added child element value filter |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 16 | # |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 17 | # Copyright (c) 2003-2009 by Fredrik Lundh. All rights reserved. |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 18 | # |
| 19 | # fredrik@pythonware.com |
| 20 | # http://www.pythonware.com |
| 21 | # |
| 22 | # -------------------------------------------------------------------- |
| 23 | # The ElementTree toolkit is |
| 24 | # |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 25 | # Copyright (c) 1999-2009 by Fredrik Lundh |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 26 | # |
| 27 | # By obtaining, using, and/or copying this software and/or its |
| 28 | # associated documentation, you agree that you have read, understood, |
| 29 | # and will comply with the following terms and conditions: |
| 30 | # |
| 31 | # Permission to use, copy, modify, and distribute this software and |
| 32 | # its associated documentation for any purpose and without fee is |
| 33 | # hereby granted, provided that the above copyright notice appears in |
| 34 | # all copies, and that both that copyright notice and this permission |
| 35 | # notice appear in supporting documentation, and that the name of |
| 36 | # Secret Labs AB or the author not be used in advertising or publicity |
| 37 | # pertaining to distribution of the software without specific, written |
| 38 | # prior permission. |
| 39 | # |
| 40 | # SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD |
| 41 | # TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT- |
| 42 | # ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR |
| 43 | # BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY |
| 44 | # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, |
| 45 | # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS |
| 46 | # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE |
| 47 | # OF THIS SOFTWARE. |
| 48 | # -------------------------------------------------------------------- |
| 49 | |
Fredrik Lundh | 63168a5 | 2005-12-14 22:29:34 +0000 | [diff] [blame] | 50 | # Licensed to PSF under a Contributor Agreement. |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 51 | # See http://www.python.org/psf/license for licensing details. |
Fredrik Lundh | 63168a5 | 2005-12-14 22:29:34 +0000 | [diff] [blame] | 52 | |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 53 | ## |
| 54 | # Implementation module for XPath support. There's usually no reason |
| 55 | # to import this module directly; the <b>ElementTree</b> does this for |
| 56 | # you, if needed. |
| 57 | ## |
| 58 | |
| 59 | import re |
| 60 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 61 | xpath_tokenizer_re = re.compile( |
R David Murray | 44b548d | 2016-09-08 13:59:53 -0400 | [diff] [blame] | 62 | r"(" |
| 63 | r"'[^']*'|\"[^\"]*\"|" |
| 64 | r"::|" |
| 65 | r"//?|" |
| 66 | r"\.\.|" |
| 67 | r"\(\)|" |
| 68 | r"[/.*:\[\]\(\)@=])|" |
| 69 | r"((?:\{[^}]+\})?[^/\[\]\(\)@=\s]+)|" |
| 70 | r"\s+" |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 71 | ) |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 72 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 73 | def xpath_tokenizer(pattern, namespaces=None): |
Stefan Behnel | e8113f5 | 2019-04-18 19:05:03 +0200 | [diff] [blame] | 74 | default_namespace = namespaces.get('') if namespaces else None |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 75 | for token in xpath_tokenizer_re.findall(pattern): |
| 76 | tag = token[1] |
Stefan Behnel | e9927e1 | 2019-04-14 10:09:09 +0200 | [diff] [blame] | 77 | if tag and tag[0] != "{": |
| 78 | if ":" in tag: |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 79 | prefix, uri = tag.split(":", 1) |
Stefan Behnel | e9927e1 | 2019-04-14 10:09:09 +0200 | [diff] [blame] | 80 | try: |
| 81 | if not namespaces: |
| 82 | raise KeyError |
| 83 | yield token[0], "{%s}%s" % (namespaces[prefix], uri) |
| 84 | except KeyError: |
| 85 | raise SyntaxError("prefix %r not found in prefix map" % prefix) from None |
| 86 | elif default_namespace: |
| 87 | yield token[0], "{%s}%s" % (default_namespace, tag) |
| 88 | else: |
| 89 | yield token |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 90 | else: |
| 91 | yield token |
| 92 | |
| 93 | def get_parent_map(context): |
| 94 | parent_map = context.parent_map |
| 95 | if parent_map is None: |
| 96 | context.parent_map = parent_map = {} |
| 97 | for p in context.root.iter(): |
| 98 | for e in p: |
| 99 | parent_map[e] = p |
| 100 | return parent_map |
| 101 | |
Stefan Behnel | 4754168 | 2019-05-03 20:58:16 +0200 | [diff] [blame] | 102 | |
| 103 | |
| 104 | def _is_wildcard_tag(tag): |
| 105 | return tag[:3] == '{*}' or tag[-2:] == '}*' |
| 106 | |
| 107 | |
| 108 | def _prepare_tag(tag): |
| 109 | _isinstance, _str = isinstance, str |
| 110 | if tag == '{*}*': |
| 111 | # Same as '*', but no comments or processing instructions. |
| 112 | # It can be a surprise that '*' includes those, but there is no |
| 113 | # justification for '{*}*' doing the same. |
| 114 | def select(context, result): |
| 115 | for elem in result: |
| 116 | if _isinstance(elem.tag, _str): |
| 117 | yield elem |
| 118 | elif tag == '{}*': |
| 119 | # Any tag that is not in a namespace. |
| 120 | def select(context, result): |
| 121 | for elem in result: |
| 122 | el_tag = elem.tag |
| 123 | if _isinstance(el_tag, _str) and el_tag[0] != '{': |
| 124 | yield elem |
| 125 | elif tag[:3] == '{*}': |
| 126 | # The tag in any (or no) namespace. |
| 127 | suffix = tag[2:] # '}name' |
| 128 | no_ns = slice(-len(suffix), None) |
| 129 | tag = tag[3:] |
| 130 | def select(context, result): |
| 131 | for elem in result: |
| 132 | el_tag = elem.tag |
| 133 | if el_tag == tag or _isinstance(el_tag, _str) and el_tag[no_ns] == suffix: |
| 134 | yield elem |
| 135 | elif tag[-2:] == '}*': |
| 136 | # Any tag in the given namespace. |
| 137 | ns = tag[:-1] |
| 138 | ns_only = slice(None, len(ns)) |
| 139 | def select(context, result): |
| 140 | for elem in result: |
| 141 | el_tag = elem.tag |
| 142 | if _isinstance(el_tag, _str) and el_tag[ns_only] == ns: |
| 143 | yield elem |
| 144 | else: |
| 145 | raise RuntimeError(f"internal parser error, got {tag}") |
| 146 | return select |
| 147 | |
| 148 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 149 | def prepare_child(next, token): |
| 150 | tag = token[1] |
Stefan Behnel | 4754168 | 2019-05-03 20:58:16 +0200 | [diff] [blame] | 151 | if _is_wildcard_tag(tag): |
| 152 | select_tag = _prepare_tag(tag) |
| 153 | def select(context, result): |
| 154 | def select_child(result): |
| 155 | for elem in result: |
| 156 | yield from elem |
| 157 | return select_tag(context, select_child(result)) |
| 158 | else: |
| 159 | if tag[:2] == '{}': |
| 160 | tag = tag[2:] # '{}tag' == 'tag' |
| 161 | def select(context, result): |
| 162 | for elem in result: |
| 163 | for e in elem: |
| 164 | if e.tag == tag: |
| 165 | yield e |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 166 | return select |
| 167 | |
| 168 | def prepare_star(next, token): |
| 169 | def select(context, result): |
| 170 | for elem in result: |
Philip Jenvey | fd0d3e5 | 2012-10-01 15:34:31 -0700 | [diff] [blame] | 171 | yield from elem |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 172 | return select |
| 173 | |
| 174 | def prepare_self(next, token): |
| 175 | def select(context, result): |
Philip Jenvey | fd0d3e5 | 2012-10-01 15:34:31 -0700 | [diff] [blame] | 176 | yield from result |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 177 | return select |
| 178 | |
| 179 | def prepare_descendant(next, token): |
Raymond Hettinger | 828d932 | 2014-11-22 21:56:23 -0800 | [diff] [blame] | 180 | try: |
| 181 | token = next() |
| 182 | except StopIteration: |
| 183 | return |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 184 | if token[0] == "*": |
| 185 | tag = "*" |
| 186 | elif not token[0]: |
| 187 | tag = token[1] |
| 188 | else: |
| 189 | raise SyntaxError("invalid descendant") |
Stefan Behnel | 4754168 | 2019-05-03 20:58:16 +0200 | [diff] [blame] | 190 | |
| 191 | if _is_wildcard_tag(tag): |
| 192 | select_tag = _prepare_tag(tag) |
| 193 | def select(context, result): |
| 194 | def select_child(result): |
| 195 | for elem in result: |
| 196 | for e in elem.iter(): |
| 197 | if e is not elem: |
| 198 | yield e |
| 199 | return select_tag(context, select_child(result)) |
| 200 | else: |
| 201 | if tag[:2] == '{}': |
| 202 | tag = tag[2:] # '{}tag' == 'tag' |
| 203 | def select(context, result): |
| 204 | for elem in result: |
| 205 | for e in elem.iter(tag): |
| 206 | if e is not elem: |
| 207 | yield e |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 208 | return select |
| 209 | |
| 210 | def prepare_parent(next, token): |
| 211 | def select(context, result): |
| 212 | # FIXME: raise error if .. is applied at toplevel? |
| 213 | parent_map = get_parent_map(context) |
| 214 | result_map = {} |
| 215 | for elem in result: |
| 216 | if elem in parent_map: |
| 217 | parent = parent_map[elem] |
| 218 | if parent not in result_map: |
| 219 | result_map[parent] = None |
| 220 | yield parent |
| 221 | return select |
| 222 | |
| 223 | def prepare_predicate(next, token): |
| 224 | # FIXME: replace with real parser!!! refs: |
| 225 | # http://effbot.org/zone/simple-iterator-parser.htm |
| 226 | # http://javascript.crockford.com/tdop/tdop.html |
| 227 | signature = [] |
| 228 | predicate = [] |
| 229 | while 1: |
Raymond Hettinger | 828d932 | 2014-11-22 21:56:23 -0800 | [diff] [blame] | 230 | try: |
| 231 | token = next() |
| 232 | except StopIteration: |
| 233 | return |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 234 | if token[0] == "]": |
| 235 | break |
scoder | 101a5e8 | 2017-09-30 15:35:21 +0200 | [diff] [blame] | 236 | if token == ('', ''): |
| 237 | # ignore whitespace |
| 238 | continue |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 239 | if token[0] and token[0][:1] in "'\"": |
| 240 | token = "'", token[0][1:-1] |
| 241 | signature.append(token[0] or "-") |
| 242 | predicate.append(token[1]) |
| 243 | signature = "".join(signature) |
| 244 | # use signature to determine predicate type |
| 245 | if signature == "@-": |
| 246 | # [@attribute] predicate |
| 247 | key = predicate[1] |
| 248 | def select(context, result): |
| 249 | for elem in result: |
| 250 | if elem.get(key) is not None: |
| 251 | yield elem |
| 252 | return select |
| 253 | if signature == "@-='": |
| 254 | # [@attribute='value'] |
| 255 | key = predicate[1] |
| 256 | value = predicate[-1] |
| 257 | def select(context, result): |
| 258 | for elem in result: |
| 259 | if elem.get(key) == value: |
| 260 | yield elem |
| 261 | return select |
R David Murray | 44b548d | 2016-09-08 13:59:53 -0400 | [diff] [blame] | 262 | if signature == "-" and not re.match(r"\-?\d+$", predicate[0]): |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 263 | # [tag] |
| 264 | tag = predicate[0] |
| 265 | def select(context, result): |
| 266 | for elem in result: |
| 267 | if elem.find(tag) is not None: |
| 268 | yield elem |
| 269 | return select |
scoder | 101a5e8 | 2017-09-30 15:35:21 +0200 | [diff] [blame] | 270 | if signature == ".='" or (signature == "-='" and not re.match(r"\-?\d+$", predicate[0])): |
| 271 | # [.='value'] or [tag='value'] |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 272 | tag = predicate[0] |
| 273 | value = predicate[-1] |
scoder | 101a5e8 | 2017-09-30 15:35:21 +0200 | [diff] [blame] | 274 | if tag: |
| 275 | def select(context, result): |
| 276 | for elem in result: |
| 277 | for e in elem.findall(tag): |
| 278 | if "".join(e.itertext()) == value: |
| 279 | yield elem |
| 280 | break |
| 281 | else: |
| 282 | def select(context, result): |
| 283 | for elem in result: |
| 284 | if "".join(elem.itertext()) == value: |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 285 | yield elem |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 286 | return select |
| 287 | if signature == "-" or signature == "-()" or signature == "-()-": |
| 288 | # [index] or [last()] or [last()-index] |
| 289 | if signature == "-": |
Eli Bendersky | 5c6198b | 2013-01-24 06:29:26 -0800 | [diff] [blame] | 290 | # [index] |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 291 | index = int(predicate[0]) - 1 |
Eli Bendersky | 5c6198b | 2013-01-24 06:29:26 -0800 | [diff] [blame] | 292 | if index < 0: |
| 293 | raise SyntaxError("XPath position >= 1 expected") |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 294 | else: |
| 295 | if predicate[0] != "last": |
| 296 | raise SyntaxError("unsupported function") |
| 297 | if signature == "-()-": |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 298 | try: |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 299 | index = int(predicate[2]) - 1 |
| 300 | except ValueError: |
| 301 | raise SyntaxError("unsupported expression") |
Eli Bendersky | 5c6198b | 2013-01-24 06:29:26 -0800 | [diff] [blame] | 302 | if index > -2: |
| 303 | raise SyntaxError("XPath offset from last() must be negative") |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 304 | else: |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 305 | index = -1 |
| 306 | def select(context, result): |
| 307 | parent_map = get_parent_map(context) |
| 308 | for elem in result: |
| 309 | try: |
| 310 | parent = parent_map[elem] |
| 311 | # FIXME: what if the selector is "*" ? |
| 312 | elems = list(parent.findall(elem.tag)) |
| 313 | if elems[index] is elem: |
| 314 | yield elem |
| 315 | except (IndexError, KeyError): |
| 316 | pass |
| 317 | return select |
| 318 | raise SyntaxError("invalid predicate") |
| 319 | |
| 320 | ops = { |
| 321 | "": prepare_child, |
| 322 | "*": prepare_star, |
| 323 | ".": prepare_self, |
| 324 | "..": prepare_parent, |
| 325 | "//": prepare_descendant, |
| 326 | "[": prepare_predicate, |
| 327 | } |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 328 | |
| 329 | _cache = {} |
| 330 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 331 | class _SelectorContext: |
| 332 | parent_map = None |
| 333 | def __init__(self, root): |
| 334 | self.root = root |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 335 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 336 | # -------------------------------------------------------------------- |
| 337 | |
| 338 | ## |
| 339 | # Generate all matching objects. |
| 340 | |
| 341 | def iterfind(elem, path, namespaces=None): |
| 342 | # compile selector pattern |
| 343 | if path[-1:] == "/": |
| 344 | path = path + "*" # implicit all (FIXME: keep this?) |
Stefan Behnel | e9927e1 | 2019-04-14 10:09:09 +0200 | [diff] [blame] | 345 | |
| 346 | cache_key = (path,) |
| 347 | if namespaces: |
Stefan Behnel | e8113f5 | 2019-04-18 19:05:03 +0200 | [diff] [blame] | 348 | cache_key += tuple(sorted(namespaces.items())) |
Stefan Behnel | e9927e1 | 2019-04-14 10:09:09 +0200 | [diff] [blame] | 349 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 350 | try: |
Eli Bendersky | 2acc525 | 2013-08-03 17:47:47 -0700 | [diff] [blame] | 351 | selector = _cache[cache_key] |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 352 | except KeyError: |
| 353 | if len(_cache) > 100: |
| 354 | _cache.clear() |
| 355 | if path[:1] == "/": |
| 356 | raise SyntaxError("cannot use absolute path on element") |
| 357 | next = iter(xpath_tokenizer(path, namespaces)).__next__ |
Raymond Hettinger | 828d932 | 2014-11-22 21:56:23 -0800 | [diff] [blame] | 358 | try: |
| 359 | token = next() |
| 360 | except StopIteration: |
| 361 | return |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 362 | selector = [] |
| 363 | while 1: |
| 364 | try: |
| 365 | selector.append(ops[token[0]](next, token)) |
| 366 | except StopIteration: |
Pablo Galindo | 0df1905 | 2017-10-16 09:24:22 +0100 | [diff] [blame] | 367 | raise SyntaxError("invalid path") from None |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 368 | try: |
| 369 | token = next() |
| 370 | if token[0] == "/": |
| 371 | token = next() |
| 372 | except StopIteration: |
| 373 | break |
Eli Bendersky | 2acc525 | 2013-08-03 17:47:47 -0700 | [diff] [blame] | 374 | _cache[cache_key] = selector |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 375 | # execute selector pattern |
| 376 | result = [elem] |
| 377 | context = _SelectorContext(elem) |
| 378 | for select in selector: |
| 379 | result = select(context, result) |
| 380 | return result |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 381 | |
| 382 | ## |
| 383 | # Find first matching object. |
| 384 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 385 | def find(elem, path, namespaces=None): |
Raymond Hettinger | 0badfd5 | 2014-11-28 14:52:14 -0800 | [diff] [blame] | 386 | return next(iterfind(elem, path, namespaces), None) |
Armin Rigo | 9ed7306 | 2005-12-14 18:10:45 +0000 | [diff] [blame] | 387 | |
| 388 | ## |
| 389 | # Find all matching objects. |
| 390 | |
Florent Xicluna | f15351d | 2010-03-13 23:24:31 +0000 | [diff] [blame] | 391 | def findall(elem, path, namespaces=None): |
| 392 | return list(iterfind(elem, path, namespaces)) |
| 393 | |
| 394 | ## |
| 395 | # Find text for first matching object. |
| 396 | |
| 397 | def findtext(elem, path, default=None, namespaces=None): |
| 398 | try: |
| 399 | elem = next(iterfind(elem, path, namespaces)) |
| 400 | return elem.text or "" |
| 401 | except StopIteration: |
| 402 | return default |