ElementPath.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. #
  2. # ElementTree
  3. # $Id: ElementPath.py 1858 2004-06-17 21:31:41Z 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. #
  12. # Copyright (c) 2003-2004 by Fredrik Lundh. All rights reserved.
  13. #
  14. # fredrik@pythonware.com
  15. # http://www.pythonware.com
  16. #
  17. # --------------------------------------------------------------------
  18. # The ElementTree toolkit is
  19. #
  20. # Copyright (c) 1999-2004 by Fredrik Lundh
  21. #
  22. # By obtaining, using, and/or copying this software and/or its
  23. # associated documentation, you agree that you have read, understood,
  24. # and will comply with the following terms and conditions:
  25. #
  26. # Permission to use, copy, modify, and distribute this software and
  27. # its associated documentation for any purpose and without fee is
  28. # hereby granted, provided that the above copyright notice appears in
  29. # all copies, and that both that copyright notice and this permission
  30. # notice appear in supporting documentation, and that the name of
  31. # Secret Labs AB or the author not be used in advertising or publicity
  32. # pertaining to distribution of the software without specific, written
  33. # prior permission.
  34. #
  35. # SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
  36. # TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
  37. # ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
  38. # BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
  39. # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
  40. # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
  41. # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
  42. # OF THIS SOFTWARE.
  43. # --------------------------------------------------------------------
  44. ##
  45. # Implementation module for XPath support. There's usually no reason
  46. # to import this module directly; the <b>ElementTree</b> does this for
  47. # you, if needed.
  48. ##
  49. import re
  50. xpath_tokenizer = re.compile(
  51. "(::|\.\.|\(\)|[/.*:\[\]\(\)@=])|((?:\{[^}]+\})?[^/:\[\]\(\)@=\s]+)|\s+"
  52. ).findall
  53. class xpath_descendant_or_self:
  54. pass
  55. ##
  56. # Wrapper for a compiled XPath.
  57. class Path:
  58. ##
  59. # Create an Path instance from an XPath expression.
  60. def __init__(self, path):
  61. tokens = xpath_tokenizer(path)
  62. # the current version supports 'path/path'-style expressions only
  63. self.path = []
  64. self.tag = None
  65. if tokens and tokens[0][0] == "/":
  66. raise SyntaxError("cannot use absolute path on element")
  67. while tokens:
  68. op, tag = tokens.pop(0)
  69. if tag or op == "*":
  70. self.path.append(tag or op)
  71. elif op == ".":
  72. pass
  73. elif op == "/":
  74. self.path.append(xpath_descendant_or_self())
  75. continue
  76. else:
  77. raise SyntaxError("unsupported path syntax (%s)" % op)
  78. if tokens:
  79. op, tag = tokens.pop(0)
  80. if op != "/":
  81. raise SyntaxError(
  82. "expected path separator (%s)" % (op or tag)
  83. )
  84. if self.path and isinstance(self.path[-1], xpath_descendant_or_self):
  85. raise SyntaxError("path cannot end with //")
  86. if len(self.path) == 1 and isinstance(self.path[0], type("")):
  87. self.tag = self.path[0]
  88. ##
  89. # Find first matching object.
  90. def find(self, element):
  91. tag = self.tag
  92. if tag is None:
  93. nodeset = self.findall(element)
  94. if not nodeset:
  95. return None
  96. return nodeset[0]
  97. for elem in element:
  98. if elem.tag == tag:
  99. return elem
  100. return None
  101. ##
  102. # Find text for first matching object.
  103. def findtext(self, element, default=None):
  104. tag = self.tag
  105. if tag is None:
  106. nodeset = self.findall(element)
  107. if not nodeset:
  108. return default
  109. return nodeset[0].text or ""
  110. for elem in element:
  111. if elem.tag == tag:
  112. return elem.text or ""
  113. return default
  114. ##
  115. # Find all matching objects.
  116. def findall(self, element):
  117. nodeset = [element]
  118. index = 0
  119. while 1:
  120. try:
  121. path = self.path[index]
  122. index = index + 1
  123. except IndexError:
  124. return nodeset
  125. set = []
  126. if isinstance(path, xpath_descendant_or_self):
  127. try:
  128. tag = self.path[index]
  129. if not isinstance(tag, type("")):
  130. tag = None
  131. else:
  132. index = index + 1
  133. except IndexError:
  134. tag = None # invalid path
  135. for node in nodeset:
  136. new = list(node.getiterator(tag))
  137. if new and new[0] is node:
  138. set.extend(new[1:])
  139. else:
  140. set.extend(new)
  141. else:
  142. for node in nodeset:
  143. for node in node:
  144. if path == "*" or node.tag == path:
  145. set.append(node)
  146. if not set:
  147. return []
  148. nodeset = set
  149. _cache = {}
  150. ##
  151. # (Internal) Compile path.
  152. def _compile(path):
  153. p = _cache.get(path)
  154. if p is not None:
  155. return p
  156. p = Path(path)
  157. if len(_cache) >= 100:
  158. _cache.clear()
  159. _cache[path] = p
  160. return p
  161. ##
  162. # Find first matching object.
  163. def find(element, path):
  164. return _compile(path).find(element)
  165. ##
  166. # Find text for first matching object.
  167. def findtext(element, path, default=None):
  168. return _compile(path).findtext(element, default)
  169. ##
  170. # Find all matching objects.
  171. def findall(element, path):
  172. return _compile(path).findall(element)