Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

domhelpers.py 8.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. # -*- test-case-name: twisted.web.test.test_domhelpers -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. A library for performing interesting tasks with DOM objects.
  6. """
  7. from io import StringIO
  8. from twisted.web import microdom
  9. from twisted.web.microdom import escape, getElementsByTagName, unescape
  10. # These modules are imported here as a shortcut.
  11. escape
  12. getElementsByTagName
  13. class NodeLookupError(Exception):
  14. pass
  15. def substitute(request, node, subs):
  16. """
  17. Look through the given node's children for strings, and
  18. attempt to do string substitution with the given parameter.
  19. """
  20. for child in node.childNodes:
  21. if hasattr(child, "nodeValue") and child.nodeValue:
  22. child.replaceData(0, len(child.nodeValue), child.nodeValue % subs)
  23. substitute(request, child, subs)
  24. def _get(node, nodeId, nodeAttrs=("id", "class", "model", "pattern")):
  25. """
  26. (internal) Get a node with the specified C{nodeId} as any of the C{class},
  27. C{id} or C{pattern} attributes.
  28. """
  29. if hasattr(node, "hasAttributes") and node.hasAttributes():
  30. for nodeAttr in nodeAttrs:
  31. if str(node.getAttribute(nodeAttr)) == nodeId:
  32. return node
  33. if node.hasChildNodes():
  34. if hasattr(node.childNodes, "length"):
  35. length = node.childNodes.length
  36. else:
  37. length = len(node.childNodes)
  38. for childNum in range(length):
  39. result = _get(node.childNodes[childNum], nodeId)
  40. if result:
  41. return result
  42. def get(node, nodeId):
  43. """
  44. Get a node with the specified C{nodeId} as any of the C{class},
  45. C{id} or C{pattern} attributes. If there is no such node, raise
  46. L{NodeLookupError}.
  47. """
  48. result = _get(node, nodeId)
  49. if result:
  50. return result
  51. raise NodeLookupError(nodeId)
  52. def getIfExists(node, nodeId):
  53. """
  54. Get a node with the specified C{nodeId} as any of the C{class},
  55. C{id} or C{pattern} attributes. If there is no such node, return
  56. L{None}.
  57. """
  58. return _get(node, nodeId)
  59. def getAndClear(node, nodeId):
  60. """Get a node with the specified C{nodeId} as any of the C{class},
  61. C{id} or C{pattern} attributes. If there is no such node, raise
  62. L{NodeLookupError}. Remove all child nodes before returning.
  63. """
  64. result = get(node, nodeId)
  65. if result:
  66. clearNode(result)
  67. return result
  68. def clearNode(node):
  69. """
  70. Remove all children from the given node.
  71. """
  72. node.childNodes[:] = []
  73. def locateNodes(nodeList, key, value, noNesting=1):
  74. """
  75. Find subnodes in the given node where the given attribute
  76. has the given value.
  77. """
  78. returnList = []
  79. if not isinstance(nodeList, type([])):
  80. return locateNodes(nodeList.childNodes, key, value, noNesting)
  81. for childNode in nodeList:
  82. if not hasattr(childNode, "getAttribute"):
  83. continue
  84. if str(childNode.getAttribute(key)) == value:
  85. returnList.append(childNode)
  86. if noNesting:
  87. continue
  88. returnList.extend(locateNodes(childNode, key, value, noNesting))
  89. return returnList
  90. def superSetAttribute(node, key, value):
  91. if not hasattr(node, "setAttribute"):
  92. return
  93. node.setAttribute(key, value)
  94. if node.hasChildNodes():
  95. for child in node.childNodes:
  96. superSetAttribute(child, key, value)
  97. def superPrependAttribute(node, key, value):
  98. if not hasattr(node, "setAttribute"):
  99. return
  100. old = node.getAttribute(key)
  101. if old:
  102. node.setAttribute(key, value + "/" + old)
  103. else:
  104. node.setAttribute(key, value)
  105. if node.hasChildNodes():
  106. for child in node.childNodes:
  107. superPrependAttribute(child, key, value)
  108. def superAppendAttribute(node, key, value):
  109. if not hasattr(node, "setAttribute"):
  110. return
  111. old = node.getAttribute(key)
  112. if old:
  113. node.setAttribute(key, old + "/" + value)
  114. else:
  115. node.setAttribute(key, value)
  116. if node.hasChildNodes():
  117. for child in node.childNodes:
  118. superAppendAttribute(child, key, value)
  119. def gatherTextNodes(iNode, dounescape=0, joinWith=""):
  120. """Visit each child node and collect its text data, if any, into a string.
  121. For example::
  122. >>> doc=microdom.parseString('<a>1<b>2<c>3</c>4</b></a>')
  123. >>> gatherTextNodes(doc.documentElement)
  124. '1234'
  125. With dounescape=1, also convert entities back into normal characters.
  126. @return: the gathered nodes as a single string
  127. @rtype: str"""
  128. gathered = []
  129. gathered_append = gathered.append
  130. slice = [iNode]
  131. while len(slice) > 0:
  132. c = slice.pop(0)
  133. if hasattr(c, "nodeValue") and c.nodeValue is not None:
  134. if dounescape:
  135. val = unescape(c.nodeValue)
  136. else:
  137. val = c.nodeValue
  138. gathered_append(val)
  139. slice[:0] = c.childNodes
  140. return joinWith.join(gathered)
  141. class RawText(microdom.Text):
  142. """This is an evil and horrible speed hack. Basically, if you have a big
  143. chunk of XML that you want to insert into the DOM, but you don't want to
  144. incur the cost of parsing it, you can construct one of these and insert it
  145. into the DOM. This will most certainly only work with microdom as the API
  146. for converting nodes to xml is different in every DOM implementation.
  147. This could be improved by making this class a Lazy parser, so if you
  148. inserted this into the DOM and then later actually tried to mutate this
  149. node, it would be parsed then.
  150. """
  151. def writexml(
  152. self,
  153. writer,
  154. indent="",
  155. addindent="",
  156. newl="",
  157. strip=0,
  158. nsprefixes=None,
  159. namespace=None,
  160. ):
  161. writer.write(f"{indent}{self.data}{newl}")
  162. def findNodes(parent, matcher, accum=None):
  163. if accum is None:
  164. accum = []
  165. if not parent.hasChildNodes():
  166. return accum
  167. for child in parent.childNodes:
  168. # print child, child.nodeType, child.nodeName
  169. if matcher(child):
  170. accum.append(child)
  171. findNodes(child, matcher, accum)
  172. return accum
  173. def findNodesShallowOnMatch(parent, matcher, recurseMatcher, accum=None):
  174. if accum is None:
  175. accum = []
  176. if not parent.hasChildNodes():
  177. return accum
  178. for child in parent.childNodes:
  179. # print child, child.nodeType, child.nodeName
  180. if matcher(child):
  181. accum.append(child)
  182. if recurseMatcher(child):
  183. findNodesShallowOnMatch(child, matcher, recurseMatcher, accum)
  184. return accum
  185. def findNodesShallow(parent, matcher, accum=None):
  186. if accum is None:
  187. accum = []
  188. if not parent.hasChildNodes():
  189. return accum
  190. for child in parent.childNodes:
  191. if matcher(child):
  192. accum.append(child)
  193. else:
  194. findNodes(child, matcher, accum)
  195. return accum
  196. def findElementsWithAttributeShallow(parent, attribute):
  197. """
  198. Return an iterable of the elements which are direct children of C{parent}
  199. and which have the C{attribute} attribute.
  200. """
  201. return findNodesShallow(
  202. parent,
  203. lambda n: getattr(n, "tagName", None) is not None and n.hasAttribute(attribute),
  204. )
  205. def findElements(parent, matcher):
  206. """
  207. Return an iterable of the elements which are children of C{parent} for
  208. which the predicate C{matcher} returns true.
  209. """
  210. return findNodes(
  211. parent,
  212. lambda n, matcher=matcher: getattr(n, "tagName", None) is not None
  213. and matcher(n),
  214. )
  215. def findElementsWithAttribute(parent, attribute, value=None):
  216. if value:
  217. return findElements(
  218. parent,
  219. lambda n, attribute=attribute, value=value: n.hasAttribute(attribute)
  220. and n.getAttribute(attribute) == value,
  221. )
  222. else:
  223. return findElements(
  224. parent, lambda n, attribute=attribute: n.hasAttribute(attribute)
  225. )
  226. def findNodesNamed(parent, name):
  227. return findNodes(parent, lambda n, name=name: n.nodeName == name)
  228. def writeNodeData(node, oldio):
  229. for subnode in node.childNodes:
  230. if hasattr(subnode, "data"):
  231. oldio.write("" + subnode.data)
  232. else:
  233. writeNodeData(subnode, oldio)
  234. def getNodeText(node):
  235. oldio = StringIO()
  236. writeNodeData(node, oldio)
  237. return oldio.getvalue()
  238. def getParents(node):
  239. l = []
  240. while node:
  241. l.append(node)
  242. node = node.parentNode
  243. return l
  244. def namedChildren(parent, nodeName):
  245. """namedChildren(parent, nodeName) -> children (not descendants) of parent
  246. that have tagName == nodeName
  247. """
  248. return [n for n in parent.childNodes if getattr(n, "tagName", "") == nodeName]