blob: ef32917b14d41e22a490d658840750d68e9493c7 [file] [log] [blame]
Armin Rigo9ed73062005-12-14 18:10:45 +00001#
2# ElementTree
Florent Xiclunaf15351d2010-03-13 23:24:31 +00003# $Id: ElementPath.py 3375 2008-02-13 08:05:08Z fredrik $
Armin Rigo9ed73062005-12-14 18:10:45 +00004#
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 Xiclunaf15351d2010-03-13 23:24:31 +000011# 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 Rigo9ed73062005-12-14 18:10:45 +000016#
Florent Xiclunaf15351d2010-03-13 23:24:31 +000017# Copyright (c) 2003-2009 by Fredrik Lundh. All rights reserved.
Armin Rigo9ed73062005-12-14 18:10:45 +000018#
19# fredrik@pythonware.com
20# http://www.pythonware.com
21#
22# --------------------------------------------------------------------
23# The ElementTree toolkit is
24#
Florent Xiclunaf15351d2010-03-13 23:24:31 +000025# Copyright (c) 1999-2009 by Fredrik Lundh
Armin Rigo9ed73062005-12-14 18:10:45 +000026#
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 Lundh63168a52005-12-14 22:29:34 +000050# Licensed to PSF under a Contributor Agreement.
Florent Xiclunaf15351d2010-03-13 23:24:31 +000051# See http://www.python.org/psf/license for licensing details.
Fredrik Lundh63168a52005-12-14 22:29:34 +000052
Armin Rigo9ed73062005-12-14 18:10:45 +000053##
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
59import re
60
Florent Xiclunaf15351d2010-03-13 23:24:31 +000061xpath_tokenizer_re = re.compile(
R David Murray44b548d2016-09-08 13:59:53 -040062 r"("
63 r"'[^']*'|\"[^\"]*\"|"
64 r"::|"
65 r"//?|"
66 r"\.\.|"
67 r"\(\)|"
68 r"[/.*:\[\]\(\)@=])|"
69 r"((?:\{[^}]+\})?[^/\[\]\(\)@=\s]+)|"
70 r"\s+"
Florent Xiclunaf15351d2010-03-13 23:24:31 +000071 )
Armin Rigo9ed73062005-12-14 18:10:45 +000072
Florent Xiclunaf15351d2010-03-13 23:24:31 +000073def xpath_tokenizer(pattern, namespaces=None):
74 for token in xpath_tokenizer_re.findall(pattern):
75 tag = token[1]
76 if tag and tag[0] != "{" and ":" in tag:
Armin Rigo9ed73062005-12-14 18:10:45 +000077 try:
Florent Xiclunaf15351d2010-03-13 23:24:31 +000078 prefix, uri = tag.split(":", 1)
79 if not namespaces:
80 raise KeyError
81 yield token[0], "{%s}%s" % (namespaces[prefix], uri)
82 except KeyError:
Serhiy Storchaka5affd232017-04-05 09:37:24 +030083 raise SyntaxError("prefix %r not found in prefix map" % prefix) from None
Florent Xiclunaf15351d2010-03-13 23:24:31 +000084 else:
85 yield token
86
87def get_parent_map(context):
88 parent_map = context.parent_map
89 if parent_map is None:
90 context.parent_map = parent_map = {}
91 for p in context.root.iter():
92 for e in p:
93 parent_map[e] = p
94 return parent_map
95
96def prepare_child(next, token):
97 tag = token[1]
98 def select(context, result):
99 for elem in result:
100 for e in elem:
101 if e.tag == tag:
102 yield e
103 return select
104
105def prepare_star(next, token):
106 def select(context, result):
107 for elem in result:
Philip Jenveyfd0d3e52012-10-01 15:34:31 -0700108 yield from elem
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000109 return select
110
111def prepare_self(next, token):
112 def select(context, result):
Philip Jenveyfd0d3e52012-10-01 15:34:31 -0700113 yield from result
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000114 return select
115
116def prepare_descendant(next, token):
Raymond Hettinger828d9322014-11-22 21:56:23 -0800117 try:
118 token = next()
119 except StopIteration:
120 return
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000121 if token[0] == "*":
122 tag = "*"
123 elif not token[0]:
124 tag = token[1]
125 else:
126 raise SyntaxError("invalid descendant")
127 def select(context, result):
128 for elem in result:
129 for e in elem.iter(tag):
130 if e is not elem:
131 yield e
132 return select
133
134def prepare_parent(next, token):
135 def select(context, result):
136 # FIXME: raise error if .. is applied at toplevel?
137 parent_map = get_parent_map(context)
138 result_map = {}
139 for elem in result:
140 if elem in parent_map:
141 parent = parent_map[elem]
142 if parent not in result_map:
143 result_map[parent] = None
144 yield parent
145 return select
146
147def prepare_predicate(next, token):
148 # FIXME: replace with real parser!!! refs:
149 # http://effbot.org/zone/simple-iterator-parser.htm
150 # http://javascript.crockford.com/tdop/tdop.html
151 signature = []
152 predicate = []
153 while 1:
Raymond Hettinger828d9322014-11-22 21:56:23 -0800154 try:
155 token = next()
156 except StopIteration:
157 return
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000158 if token[0] == "]":
159 break
scoder101a5e82017-09-30 15:35:21 +0200160 if token == ('', ''):
161 # ignore whitespace
162 continue
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000163 if token[0] and token[0][:1] in "'\"":
164 token = "'", token[0][1:-1]
165 signature.append(token[0] or "-")
166 predicate.append(token[1])
167 signature = "".join(signature)
168 # use signature to determine predicate type
169 if signature == "@-":
170 # [@attribute] predicate
171 key = predicate[1]
172 def select(context, result):
173 for elem in result:
174 if elem.get(key) is not None:
175 yield elem
176 return select
177 if signature == "@-='":
178 # [@attribute='value']
179 key = predicate[1]
180 value = predicate[-1]
181 def select(context, result):
182 for elem in result:
183 if elem.get(key) == value:
184 yield elem
185 return select
R David Murray44b548d2016-09-08 13:59:53 -0400186 if signature == "-" and not re.match(r"\-?\d+$", predicate[0]):
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000187 # [tag]
188 tag = predicate[0]
189 def select(context, result):
190 for elem in result:
191 if elem.find(tag) is not None:
192 yield elem
193 return select
scoder101a5e82017-09-30 15:35:21 +0200194 if signature == ".='" or (signature == "-='" and not re.match(r"\-?\d+$", predicate[0])):
195 # [.='value'] or [tag='value']
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000196 tag = predicate[0]
197 value = predicate[-1]
scoder101a5e82017-09-30 15:35:21 +0200198 if tag:
199 def select(context, result):
200 for elem in result:
201 for e in elem.findall(tag):
202 if "".join(e.itertext()) == value:
203 yield elem
204 break
205 else:
206 def select(context, result):
207 for elem in result:
208 if "".join(elem.itertext()) == value:
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000209 yield elem
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000210 return select
211 if signature == "-" or signature == "-()" or signature == "-()-":
212 # [index] or [last()] or [last()-index]
213 if signature == "-":
Eli Bendersky5c6198b2013-01-24 06:29:26 -0800214 # [index]
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000215 index = int(predicate[0]) - 1
Eli Bendersky5c6198b2013-01-24 06:29:26 -0800216 if index < 0:
217 raise SyntaxError("XPath position >= 1 expected")
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000218 else:
219 if predicate[0] != "last":
220 raise SyntaxError("unsupported function")
221 if signature == "-()-":
Armin Rigo9ed73062005-12-14 18:10:45 +0000222 try:
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000223 index = int(predicate[2]) - 1
224 except ValueError:
225 raise SyntaxError("unsupported expression")
Eli Bendersky5c6198b2013-01-24 06:29:26 -0800226 if index > -2:
227 raise SyntaxError("XPath offset from last() must be negative")
Armin Rigo9ed73062005-12-14 18:10:45 +0000228 else:
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000229 index = -1
230 def select(context, result):
231 parent_map = get_parent_map(context)
232 for elem in result:
233 try:
234 parent = parent_map[elem]
235 # FIXME: what if the selector is "*" ?
236 elems = list(parent.findall(elem.tag))
237 if elems[index] is elem:
238 yield elem
239 except (IndexError, KeyError):
240 pass
241 return select
242 raise SyntaxError("invalid predicate")
243
244ops = {
245 "": prepare_child,
246 "*": prepare_star,
247 ".": prepare_self,
248 "..": prepare_parent,
249 "//": prepare_descendant,
250 "[": prepare_predicate,
251 }
Armin Rigo9ed73062005-12-14 18:10:45 +0000252
253_cache = {}
254
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000255class _SelectorContext:
256 parent_map = None
257 def __init__(self, root):
258 self.root = root
Armin Rigo9ed73062005-12-14 18:10:45 +0000259
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000260# --------------------------------------------------------------------
261
262##
263# Generate all matching objects.
264
265def iterfind(elem, path, namespaces=None):
266 # compile selector pattern
Eli Bendersky2acc5252013-08-03 17:47:47 -0700267 cache_key = (path, None if namespaces is None
268 else tuple(sorted(namespaces.items())))
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000269 if path[-1:] == "/":
270 path = path + "*" # implicit all (FIXME: keep this?)
271 try:
Eli Bendersky2acc5252013-08-03 17:47:47 -0700272 selector = _cache[cache_key]
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000273 except KeyError:
274 if len(_cache) > 100:
275 _cache.clear()
276 if path[:1] == "/":
277 raise SyntaxError("cannot use absolute path on element")
278 next = iter(xpath_tokenizer(path, namespaces)).__next__
Raymond Hettinger828d9322014-11-22 21:56:23 -0800279 try:
280 token = next()
281 except StopIteration:
282 return
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000283 selector = []
284 while 1:
285 try:
286 selector.append(ops[token[0]](next, token))
287 except StopIteration:
Pablo Galindo0df19052017-10-16 09:24:22 +0100288 raise SyntaxError("invalid path") from None
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000289 try:
290 token = next()
291 if token[0] == "/":
292 token = next()
293 except StopIteration:
294 break
Eli Bendersky2acc5252013-08-03 17:47:47 -0700295 _cache[cache_key] = selector
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000296 # execute selector pattern
297 result = [elem]
298 context = _SelectorContext(elem)
299 for select in selector:
300 result = select(context, result)
301 return result
Armin Rigo9ed73062005-12-14 18:10:45 +0000302
303##
304# Find first matching object.
305
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000306def find(elem, path, namespaces=None):
Raymond Hettinger0badfd52014-11-28 14:52:14 -0800307 return next(iterfind(elem, path, namespaces), None)
Armin Rigo9ed73062005-12-14 18:10:45 +0000308
309##
310# Find all matching objects.
311
Florent Xiclunaf15351d2010-03-13 23:24:31 +0000312def findall(elem, path, namespaces=None):
313 return list(iterfind(elem, path, namespaces))
314
315##
316# Find text for first matching object.
317
318def findtext(elem, path, default=None, namespaces=None):
319 try:
320 elem = next(iterfind(elem, path, namespaces))
321 return elem.text or ""
322 except StopIteration:
323 return default