Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 

346 řádky
10 KiB

  1. # cython: language_level=2
  2. #
  3. # ElementTree
  4. # $Id: ElementPath.py 3375 2008-02-13 08:05:08Z fredrik $
  5. #
  6. # limited xpath support for element trees
  7. #
  8. # history:
  9. # 2003-05-23 fl created
  10. # 2003-05-28 fl added support for // etc
  11. # 2003-08-27 fl fixed parsing of periods in element names
  12. # 2007-09-10 fl new selection engine
  13. # 2007-09-12 fl fixed parent selector
  14. # 2007-09-13 fl added iterfind; changed findall to return a list
  15. # 2007-11-30 fl added namespaces support
  16. # 2009-10-30 fl added child element value filter
  17. #
  18. # Copyright (c) 2003-2009 by Fredrik Lundh. All rights reserved.
  19. #
  20. # fredrik@pythonware.com
  21. # http://www.pythonware.com
  22. #
  23. # --------------------------------------------------------------------
  24. # The ElementTree toolkit is
  25. #
  26. # Copyright (c) 1999-2009 by Fredrik Lundh
  27. #
  28. # By obtaining, using, and/or copying this software and/or its
  29. # associated documentation, you agree that you have read, understood,
  30. # and will comply with the following terms and conditions:
  31. #
  32. # Permission to use, copy, modify, and distribute this software and
  33. # its associated documentation for any purpose and without fee is
  34. # hereby granted, provided that the above copyright notice appears in
  35. # all copies, and that both that copyright notice and this permission
  36. # notice appear in supporting documentation, and that the name of
  37. # Secret Labs AB or the author not be used in advertising or publicity
  38. # pertaining to distribution of the software without specific, written
  39. # prior permission.
  40. #
  41. # SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
  42. # TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
  43. # ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
  44. # BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
  45. # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
  46. # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
  47. # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
  48. # OF THIS SOFTWARE.
  49. # --------------------------------------------------------------------
  50. ##
  51. # Implementation module for XPath support. There's usually no reason
  52. # to import this module directly; the <b>ElementTree</b> does this for
  53. # you, if needed.
  54. ##
  55. from __future__ import absolute_import
  56. import re
  57. xpath_tokenizer_re = re.compile(
  58. "("
  59. "'[^']*'|\"[^\"]*\"|"
  60. "::|"
  61. "//?|"
  62. r"\.\.|"
  63. r"\(\)|"
  64. r"[/.*:\[\]\(\)@=])|"
  65. r"((?:\{[^}]+\})?[^/\[\]\(\)@=\s]+)|"
  66. r"\s+"
  67. )
  68. def xpath_tokenizer(pattern, namespaces=None):
  69. # ElementTree uses '', lxml used None originally.
  70. default_namespace = (namespaces.get(None) or 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)
  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 prepare_child(next, token):
  92. tag = token[1]
  93. def select(result):
  94. for elem in result:
  95. for e in elem.iterchildren(tag):
  96. yield e
  97. return select
  98. def prepare_star(next, token):
  99. def select(result):
  100. for elem in result:
  101. for e in elem.iterchildren('*'):
  102. yield e
  103. return select
  104. def prepare_self(next, token):
  105. def select(result):
  106. return result
  107. return select
  108. def prepare_descendant(next, token):
  109. token = next()
  110. if token[0] == "*":
  111. tag = "*"
  112. elif not token[0]:
  113. tag = token[1]
  114. else:
  115. raise SyntaxError("invalid descendant")
  116. def select(result):
  117. for elem in result:
  118. for e in elem.iterdescendants(tag):
  119. yield e
  120. return select
  121. def prepare_parent(next, token):
  122. def select(result):
  123. for elem in result:
  124. parent = elem.getparent()
  125. if parent is not None:
  126. yield parent
  127. return select
  128. def prepare_predicate(next, token):
  129. # FIXME: replace with real parser!!! refs:
  130. # http://effbot.org/zone/simple-iterator-parser.htm
  131. # http://javascript.crockford.com/tdop/tdop.html
  132. signature = ''
  133. predicate = []
  134. while 1:
  135. token = next()
  136. if token[0] == "]":
  137. break
  138. if token == ('', ''):
  139. # ignore whitespace
  140. continue
  141. if token[0] and token[0][:1] in "'\"":
  142. token = "'", token[0][1:-1]
  143. signature += token[0] or "-"
  144. predicate.append(token[1])
  145. # use signature to determine predicate type
  146. if signature == "@-":
  147. # [@attribute] predicate
  148. key = predicate[1]
  149. def select(result):
  150. for elem in result:
  151. if elem.get(key) is not None:
  152. yield elem
  153. return select
  154. if signature == "@-='":
  155. # [@attribute='value']
  156. key = predicate[1]
  157. value = predicate[-1]
  158. def select(result):
  159. for elem in result:
  160. if elem.get(key) == value:
  161. yield elem
  162. return select
  163. if signature == "-" and not re.match(r"-?\d+$", predicate[0]):
  164. # [tag]
  165. tag = predicate[0]
  166. def select(result):
  167. for elem in result:
  168. for _ in elem.iterchildren(tag):
  169. yield elem
  170. break
  171. return select
  172. if signature == ".='" or (signature == "-='" and not re.match(r"-?\d+$", predicate[0])):
  173. # [.='value'] or [tag='value']
  174. tag = predicate[0]
  175. value = predicate[-1]
  176. if tag:
  177. def select(result):
  178. for elem in result:
  179. for e in elem.iterchildren(tag):
  180. if "".join(e.itertext()) == value:
  181. yield elem
  182. break
  183. else:
  184. def select(result):
  185. for elem in result:
  186. if "".join(elem.itertext()) == value:
  187. yield elem
  188. return select
  189. if signature == "-" or signature == "-()" or signature == "-()-":
  190. # [index] or [last()] or [last()-index]
  191. if signature == "-":
  192. # [index]
  193. index = int(predicate[0]) - 1
  194. if index < 0:
  195. if index == -1:
  196. raise SyntaxError(
  197. "indices in path predicates are 1-based, not 0-based")
  198. else:
  199. raise SyntaxError("path index >= 1 expected")
  200. else:
  201. if predicate[0] != "last":
  202. raise SyntaxError("unsupported function")
  203. if signature == "-()-":
  204. try:
  205. index = int(predicate[2]) - 1
  206. except ValueError:
  207. raise SyntaxError("unsupported expression")
  208. else:
  209. index = -1
  210. def select(result):
  211. for elem in result:
  212. parent = elem.getparent()
  213. if parent is None:
  214. continue
  215. try:
  216. # FIXME: what if the selector is "*" ?
  217. elems = list(parent.iterchildren(elem.tag))
  218. if elems[index] is elem:
  219. yield elem
  220. except IndexError:
  221. pass
  222. return select
  223. raise SyntaxError("invalid predicate")
  224. ops = {
  225. "": prepare_child,
  226. "*": prepare_star,
  227. ".": prepare_self,
  228. "..": prepare_parent,
  229. "//": prepare_descendant,
  230. "[": prepare_predicate,
  231. }
  232. # --------------------------------------------------------------------
  233. _cache = {}
  234. def _build_path_iterator(path, namespaces):
  235. """compile selector pattern"""
  236. if path[-1:] == "/":
  237. path += "*" # implicit all (FIXME: keep this?)
  238. cache_key = (path,)
  239. if namespaces:
  240. # lxml originally used None for the default namespace but ElementTree uses the
  241. # more convenient (all-strings-dict) empty string, so we support both here,
  242. # preferring the more convenient '', as long as they aren't ambiguous.
  243. if None in namespaces:
  244. if '' in namespaces and namespaces[None] != namespaces['']:
  245. raise ValueError("Ambiguous default namespace provided: %r versus %r" % (
  246. namespaces[None], namespaces['']))
  247. cache_key += (namespaces[None],) + tuple(sorted(
  248. item for item in namespaces.items() if item[0] is not None))
  249. else:
  250. cache_key += tuple(sorted(namespaces.items()))
  251. try:
  252. return _cache[cache_key]
  253. except KeyError:
  254. pass
  255. if len(_cache) > 100:
  256. _cache.clear()
  257. if path[:1] == "/":
  258. raise SyntaxError("cannot use absolute path on element")
  259. stream = iter(xpath_tokenizer(path, namespaces))
  260. try:
  261. _next = stream.next
  262. except AttributeError:
  263. # Python 3
  264. _next = stream.__next__
  265. try:
  266. token = _next()
  267. except StopIteration:
  268. raise SyntaxError("empty path expression")
  269. selector = []
  270. while 1:
  271. try:
  272. selector.append(ops[token[0]](_next, token))
  273. except StopIteration:
  274. raise SyntaxError("invalid path")
  275. try:
  276. token = _next()
  277. if token[0] == "/":
  278. token = _next()
  279. except StopIteration:
  280. break
  281. _cache[cache_key] = selector
  282. return selector
  283. ##
  284. # Iterate over the matching nodes
  285. def iterfind(elem, path, namespaces=None):
  286. selector = _build_path_iterator(path, namespaces)
  287. result = iter((elem,))
  288. for select in selector:
  289. result = select(result)
  290. return result
  291. ##
  292. # Find first matching object.
  293. def find(elem, path, namespaces=None):
  294. it = iterfind(elem, path, namespaces)
  295. try:
  296. return next(it)
  297. except StopIteration:
  298. return None
  299. ##
  300. # Find all matching objects.
  301. def findall(elem, path, namespaces=None):
  302. return list(iterfind(elem, path, namespaces))
  303. ##
  304. # Find text for first matching object.
  305. def findtext(elem, path, default=None, namespaces=None):
  306. el = find(elem, path, namespaces)
  307. if el is None:
  308. return default
  309. else:
  310. return el.text or ''