ElementPath.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. #
  2. # ElementTree
  3. # $Id: ElementPath.py 3375 2008-02-13 08:05:08Z fredrik $
  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
  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
  16. #
  17. # Copyright (c) 2003-2009 by Fredrik Lundh. All rights reserved.
  18. #
  19. # fredrik@pythonware.com
  20. # http://www.pythonware.com
  21. #
  22. # --------------------------------------------------------------------
  23. # The ElementTree toolkit is
  24. #
  25. # Copyright (c) 1999-2009 by Fredrik Lundh
  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. # Licensed to PSF under a Contributor Agreement.
  50. # See https://www.python.org/psf/license for licensing details.
  51. ##
  52. # Implementation module for XPath support. There's usually no reason
  53. # to import this module directly; the <b>ElementTree</b> does this for
  54. # you, if needed.
  55. ##
  56. import re
  57. xpath_tokenizer_re = re.compile(
  58. r"("
  59. r"'[^']*'|\"[^\"]*\"|"
  60. r"::|"
  61. r"//?|"
  62. r"\.\.|"
  63. r"\(\)|"
  64. r"!=|"
  65. r"[/.*:\[\]\(\)@=])|"
  66. r"((?:\{[^}]+\})?[^/\[\]\(\)@!=\s]+)|"
  67. r"\s+"
  68. )
  69. def xpath_tokenizer(pattern, namespaces=None):
  70. default_namespace = namespaces.get('') if namespaces else None
  71. parsing_attribute = False
  72. for token in xpath_tokenizer_re.findall(pattern):
  73. ttype, tag = token
  74. if tag and tag[0] != "{":
  75. if ":" in tag:
  76. prefix, uri = tag.split(":", 1)
  77. try:
  78. if not namespaces:
  79. raise KeyError
  80. yield ttype, "{%s}%s" % (namespaces[prefix], uri)
  81. except KeyError:
  82. raise SyntaxError("prefix %r not found in prefix map" % prefix) from None
  83. elif default_namespace and not parsing_attribute:
  84. yield ttype, "{%s}%s" % (default_namespace, tag)
  85. else:
  86. yield token
  87. parsing_attribute = False
  88. else:
  89. yield token
  90. parsing_attribute = ttype == '@'
  91. def get_parent_map(context):
  92. parent_map = context.parent_map
  93. if parent_map is None:
  94. context.parent_map = parent_map = {}
  95. for p in context.root.iter():
  96. for e in p:
  97. parent_map[e] = p
  98. return parent_map
  99. def _is_wildcard_tag(tag):
  100. return tag[:3] == '{*}' or tag[-2:] == '}*'
  101. def _prepare_tag(tag):
  102. _isinstance, _str = isinstance, str
  103. if tag == '{*}*':
  104. # Same as '*', but no comments or processing instructions.
  105. # It can be a surprise that '*' includes those, but there is no
  106. # justification for '{*}*' doing the same.
  107. def select(context, result):
  108. for elem in result:
  109. if _isinstance(elem.tag, _str):
  110. yield elem
  111. elif tag == '{}*':
  112. # Any tag that is not in a namespace.
  113. def select(context, result):
  114. for elem in result:
  115. el_tag = elem.tag
  116. if _isinstance(el_tag, _str) and el_tag[0] != '{':
  117. yield elem
  118. elif tag[:3] == '{*}':
  119. # The tag in any (or no) namespace.
  120. suffix = tag[2:] # '}name'
  121. no_ns = slice(-len(suffix), None)
  122. tag = tag[3:]
  123. def select(context, result):
  124. for elem in result:
  125. el_tag = elem.tag
  126. if el_tag == tag or _isinstance(el_tag, _str) and el_tag[no_ns] == suffix:
  127. yield elem
  128. elif tag[-2:] == '}*':
  129. # Any tag in the given namespace.
  130. ns = tag[:-1]
  131. ns_only = slice(None, len(ns))
  132. def select(context, result):
  133. for elem in result:
  134. el_tag = elem.tag
  135. if _isinstance(el_tag, _str) and el_tag[ns_only] == ns:
  136. yield elem
  137. else:
  138. raise RuntimeError(f"internal parser error, got {tag}")
  139. return select
  140. def prepare_child(next, token):
  141. tag = token[1]
  142. if _is_wildcard_tag(tag):
  143. select_tag = _prepare_tag(tag)
  144. def select(context, result):
  145. def select_child(result):
  146. for elem in result:
  147. yield from elem
  148. return select_tag(context, select_child(result))
  149. else:
  150. if tag[:2] == '{}':
  151. tag = tag[2:] # '{}tag' == 'tag'
  152. def select(context, result):
  153. for elem in result:
  154. for e in elem:
  155. if e.tag == tag:
  156. yield e
  157. return select
  158. def prepare_star(next, token):
  159. def select(context, result):
  160. for elem in result:
  161. yield from elem
  162. return select
  163. def prepare_self(next, token):
  164. def select(context, result):
  165. yield from result
  166. return select
  167. def prepare_descendant(next, token):
  168. try:
  169. token = next()
  170. except StopIteration:
  171. return
  172. if token[0] == "*":
  173. tag = "*"
  174. elif not token[0]:
  175. tag = token[1]
  176. else:
  177. raise SyntaxError("invalid descendant")
  178. if _is_wildcard_tag(tag):
  179. select_tag = _prepare_tag(tag)
  180. def select(context, result):
  181. def select_child(result):
  182. for elem in result:
  183. for e in elem.iter():
  184. if e is not elem:
  185. yield e
  186. return select_tag(context, select_child(result))
  187. else:
  188. if tag[:2] == '{}':
  189. tag = tag[2:] # '{}tag' == 'tag'
  190. def select(context, result):
  191. for elem in result:
  192. for e in elem.iter(tag):
  193. if e is not elem:
  194. yield e
  195. return select
  196. def prepare_parent(next, token):
  197. def select(context, result):
  198. # FIXME: raise error if .. is applied at toplevel?
  199. parent_map = get_parent_map(context)
  200. result_map = {}
  201. for elem in result:
  202. if elem in parent_map:
  203. parent = parent_map[elem]
  204. if parent not in result_map:
  205. result_map[parent] = None
  206. yield parent
  207. return select
  208. def prepare_predicate(next, token):
  209. # FIXME: replace with real parser!!! refs:
  210. # http://javascript.crockford.com/tdop/tdop.html
  211. signature = []
  212. predicate = []
  213. while 1:
  214. try:
  215. token = next()
  216. except StopIteration:
  217. return
  218. if token[0] == "]":
  219. break
  220. if token == ('', ''):
  221. # ignore whitespace
  222. continue
  223. if token[0] and token[0][:1] in "'\"":
  224. token = "'", token[0][1:-1]
  225. signature.append(token[0] or "-")
  226. predicate.append(token[1])
  227. signature = "".join(signature)
  228. # use signature to determine predicate type
  229. if signature == "@-":
  230. # [@attribute] predicate
  231. key = predicate[1]
  232. def select(context, result):
  233. for elem in result:
  234. if elem.get(key) is not None:
  235. yield elem
  236. return select
  237. if signature == "@-='" or signature == "@-!='":
  238. # [@attribute='value'] or [@attribute!='value']
  239. key = predicate[1]
  240. value = predicate[-1]
  241. def select(context, result):
  242. for elem in result:
  243. if elem.get(key) == value:
  244. yield elem
  245. def select_negated(context, result):
  246. for elem in result:
  247. if (attr_value := elem.get(key)) is not None and attr_value != value:
  248. yield elem
  249. return select_negated if '!=' in signature else select
  250. if signature == "-" and not re.match(r"\-?\d+$", predicate[0]):
  251. # [tag]
  252. tag = predicate[0]
  253. def select(context, result):
  254. for elem in result:
  255. if elem.find(tag) is not None:
  256. yield elem
  257. return select
  258. if signature == ".='" or signature == ".!='" or (
  259. (signature == "-='" or signature == "-!='")
  260. and not re.match(r"\-?\d+$", predicate[0])):
  261. # [.='value'] or [tag='value'] or [.!='value'] or [tag!='value']
  262. tag = predicate[0]
  263. value = predicate[-1]
  264. if tag:
  265. def select(context, result):
  266. for elem in result:
  267. for e in elem.findall(tag):
  268. if "".join(e.itertext()) == value:
  269. yield elem
  270. break
  271. def select_negated(context, result):
  272. for elem in result:
  273. for e in elem.iterfind(tag):
  274. if "".join(e.itertext()) != value:
  275. yield elem
  276. break
  277. else:
  278. def select(context, result):
  279. for elem in result:
  280. if "".join(elem.itertext()) == value:
  281. yield elem
  282. def select_negated(context, result):
  283. for elem in result:
  284. if "".join(elem.itertext()) != value:
  285. yield elem
  286. return select_negated if '!=' in signature else select
  287. if signature == "-" or signature == "-()" or signature == "-()-":
  288. # [index] or [last()] or [last()-index]
  289. if signature == "-":
  290. # [index]
  291. index = int(predicate[0]) - 1
  292. if index < 0:
  293. raise SyntaxError("XPath position >= 1 expected")
  294. else:
  295. if predicate[0] != "last":
  296. raise SyntaxError("unsupported function")
  297. if signature == "-()-":
  298. try:
  299. index = int(predicate[2]) - 1
  300. except ValueError:
  301. raise SyntaxError("unsupported expression")
  302. if index > -2:
  303. raise SyntaxError("XPath offset from last() must be negative")
  304. else:
  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. ops = {
  320. "": prepare_child,
  321. "*": prepare_star,
  322. ".": prepare_self,
  323. "..": prepare_parent,
  324. "//": prepare_descendant,
  325. "[": prepare_predicate,
  326. }
  327. _cache = {}
  328. class _SelectorContext:
  329. parent_map = None
  330. def __init__(self, root):
  331. self.root = root
  332. # --------------------------------------------------------------------
  333. ##
  334. # Generate all matching objects.
  335. def iterfind(elem, path, namespaces=None):
  336. # compile selector pattern
  337. if path[-1:] == "/":
  338. path = path + "*" # implicit all (FIXME: keep this?)
  339. cache_key = (path,)
  340. if namespaces:
  341. cache_key += tuple(sorted(namespaces.items()))
  342. try:
  343. selector = _cache[cache_key]
  344. except KeyError:
  345. if len(_cache) > 100:
  346. _cache.clear()
  347. if path[:1] == "/":
  348. raise SyntaxError("cannot use absolute path on element")
  349. next = iter(xpath_tokenizer(path, namespaces)).__next__
  350. try:
  351. token = next()
  352. except StopIteration:
  353. return
  354. selector = []
  355. while 1:
  356. try:
  357. selector.append(ops[token[0]](next, token))
  358. except StopIteration:
  359. raise SyntaxError("invalid path") from None
  360. try:
  361. token = next()
  362. if token[0] == "/":
  363. token = next()
  364. except StopIteration:
  365. break
  366. _cache[cache_key] = selector
  367. # execute selector pattern
  368. result = [elem]
  369. context = _SelectorContext(elem)
  370. for select in selector:
  371. result = select(context, result)
  372. return result
  373. ##
  374. # Find first matching object.
  375. def find(elem, path, namespaces=None):
  376. return next(iterfind(elem, path, namespaces), None)
  377. ##
  378. # Find all matching objects.
  379. def findall(elem, path, namespaces=None):
  380. return list(iterfind(elem, path, namespaces))
  381. ##
  382. # Find text for first matching object.
  383. def findtext(elem, path, default=None, namespaces=None):
  384. try:
  385. elem = next(iterfind(elem, path, namespaces))
  386. if elem.text is None:
  387. return ""
  388. return elem.text
  389. except StopIteration:
  390. return default