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.

microdom.py 36KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209
  1. # -*- test-case-name: twisted.web.test.test_xml -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Micro Document Object Model: a partial DOM implementation with SUX.
  6. This is an implementation of what we consider to be the useful subset of the
  7. DOM. The chief advantage of this library is that, not being burdened with
  8. standards compliance, it can remain very stable between versions. We can also
  9. implement utility 'pythonic' ways to access and mutate the XML tree.
  10. Since this has not subjected to a serious trial by fire, it is not recommended
  11. to use this outside of Twisted applications. However, it seems to work just
  12. fine for the documentation generator, which parses a fairly representative
  13. sample of XML.
  14. Microdom mainly focuses on working with HTML and XHTML.
  15. """
  16. # System Imports
  17. import re
  18. from io import BytesIO, StringIO
  19. # Twisted Imports
  20. from twisted.python.compat import ioType
  21. from twisted.python.util import InsensitiveDict
  22. from twisted.web.sux import ParseError, XMLParser
  23. def getElementsByTagName(iNode, name):
  24. """
  25. Return a list of all child elements of C{iNode} with a name matching
  26. C{name}.
  27. Note that this implementation does not conform to the DOM Level 1 Core
  28. specification because it may return C{iNode}.
  29. @param iNode: An element at which to begin searching. If C{iNode} has a
  30. name matching C{name}, it will be included in the result.
  31. @param name: A C{str} giving the name of the elements to return.
  32. @return: A C{list} of direct or indirect child elements of C{iNode} with
  33. the name C{name}. This may include C{iNode}.
  34. """
  35. matches = []
  36. matches_append = matches.append # faster lookup. don't do this at home
  37. slice = [iNode]
  38. while len(slice) > 0:
  39. c = slice.pop(0)
  40. if c.nodeName == name:
  41. matches_append(c)
  42. slice[:0] = c.childNodes
  43. return matches
  44. def getElementsByTagNameNoCase(iNode, name):
  45. name = name.lower()
  46. matches = []
  47. matches_append = matches.append
  48. slice = [iNode]
  49. while len(slice) > 0:
  50. c = slice.pop(0)
  51. if c.nodeName.lower() == name:
  52. matches_append(c)
  53. slice[:0] = c.childNodes
  54. return matches
  55. def _streamWriteWrapper(stream):
  56. if ioType(stream) == bytes:
  57. def w(s):
  58. if isinstance(s, str):
  59. s = s.encode("utf-8")
  60. stream.write(s)
  61. else:
  62. def w(s):
  63. if isinstance(s, bytes):
  64. s = s.decode("utf-8")
  65. stream.write(s)
  66. return w
  67. # order is important
  68. HTML_ESCAPE_CHARS = (
  69. ("&", "&"), # don't add any entities before this one
  70. ("<", "&lt;"),
  71. (">", "&gt;"),
  72. ('"', "&quot;"),
  73. )
  74. REV_HTML_ESCAPE_CHARS = list(HTML_ESCAPE_CHARS)
  75. REV_HTML_ESCAPE_CHARS.reverse()
  76. XML_ESCAPE_CHARS = HTML_ESCAPE_CHARS + (("'", "&apos;"),)
  77. REV_XML_ESCAPE_CHARS = list(XML_ESCAPE_CHARS)
  78. REV_XML_ESCAPE_CHARS.reverse()
  79. def unescape(text, chars=REV_HTML_ESCAPE_CHARS):
  80. """
  81. Perform the exact opposite of 'escape'.
  82. """
  83. for s, h in chars:
  84. text = text.replace(h, s)
  85. return text
  86. def escape(text, chars=HTML_ESCAPE_CHARS):
  87. """
  88. Escape a few XML special chars with XML entities.
  89. """
  90. for s, h in chars:
  91. text = text.replace(s, h)
  92. return text
  93. class MismatchedTags(Exception):
  94. def __init__(self, filename, expect, got, endLine, endCol, begLine, begCol):
  95. (
  96. self.filename,
  97. self.expect,
  98. self.got,
  99. self.begLine,
  100. self.begCol,
  101. self.endLine,
  102. self.endCol,
  103. ) = (filename, expect, got, begLine, begCol, endLine, endCol)
  104. def __str__(self) -> str:
  105. return (
  106. "expected </%s>, got </%s> line: %s col: %s, "
  107. "began line: %s col: %s"
  108. % (
  109. self.expect,
  110. self.got,
  111. self.endLine,
  112. self.endCol,
  113. self.begLine,
  114. self.begCol,
  115. )
  116. )
  117. class Node:
  118. nodeName = "Node"
  119. def __init__(self, parentNode=None):
  120. self.parentNode = parentNode
  121. self.childNodes = []
  122. def isEqualToNode(self, other):
  123. """
  124. Compare this node to C{other}. If the nodes have the same number of
  125. children and corresponding children are equal to each other, return
  126. C{True}, otherwise return C{False}.
  127. @type other: L{Node}
  128. @rtype: C{bool}
  129. """
  130. if len(self.childNodes) != len(other.childNodes):
  131. return False
  132. for a, b in zip(self.childNodes, other.childNodes):
  133. if not a.isEqualToNode(b):
  134. return False
  135. return True
  136. def writexml(
  137. self,
  138. stream,
  139. indent="",
  140. addindent="",
  141. newl="",
  142. strip=0,
  143. nsprefixes={},
  144. namespace="",
  145. ):
  146. raise NotImplementedError()
  147. def toxml(
  148. self, indent="", addindent="", newl="", strip=0, nsprefixes={}, namespace=""
  149. ):
  150. s = StringIO()
  151. self.writexml(s, indent, addindent, newl, strip, nsprefixes, namespace)
  152. rv = s.getvalue()
  153. return rv
  154. def writeprettyxml(self, stream, indent="", addindent=" ", newl="\n", strip=0):
  155. return self.writexml(stream, indent, addindent, newl, strip)
  156. def toprettyxml(self, indent="", addindent=" ", newl="\n", strip=0):
  157. return self.toxml(indent, addindent, newl, strip)
  158. def cloneNode(self, deep=0, parent=None):
  159. raise NotImplementedError()
  160. def hasChildNodes(self):
  161. if self.childNodes:
  162. return 1
  163. else:
  164. return 0
  165. def appendChild(self, child):
  166. """
  167. Make the given L{Node} the last child of this node.
  168. @param child: The L{Node} which will become a child of this node.
  169. @raise TypeError: If C{child} is not a C{Node} instance.
  170. """
  171. if not isinstance(child, Node):
  172. raise TypeError("expected Node instance")
  173. self.childNodes.append(child)
  174. child.parentNode = self
  175. def insertBefore(self, new, ref):
  176. """
  177. Make the given L{Node} C{new} a child of this node which comes before
  178. the L{Node} C{ref}.
  179. @param new: A L{Node} which will become a child of this node.
  180. @param ref: A L{Node} which is already a child of this node which
  181. C{new} will be inserted before.
  182. @raise TypeError: If C{new} or C{ref} is not a C{Node} instance.
  183. @return: C{new}
  184. """
  185. if not isinstance(new, Node) or not isinstance(ref, Node):
  186. raise TypeError("expected Node instance")
  187. i = self.childNodes.index(ref)
  188. new.parentNode = self
  189. self.childNodes.insert(i, new)
  190. return new
  191. def removeChild(self, child):
  192. """
  193. Remove the given L{Node} from this node's children.
  194. @param child: A L{Node} which is a child of this node which will no
  195. longer be a child of this node after this method is called.
  196. @raise TypeError: If C{child} is not a C{Node} instance.
  197. @return: C{child}
  198. """
  199. if not isinstance(child, Node):
  200. raise TypeError("expected Node instance")
  201. if child in self.childNodes:
  202. self.childNodes.remove(child)
  203. child.parentNode = None
  204. return child
  205. def replaceChild(self, newChild, oldChild):
  206. """
  207. Replace a L{Node} which is already a child of this node with a
  208. different node.
  209. @param newChild: A L{Node} which will be made a child of this node.
  210. @param oldChild: A L{Node} which is a child of this node which will
  211. give up its position to C{newChild}.
  212. @raise TypeError: If C{newChild} or C{oldChild} is not a C{Node}
  213. instance.
  214. @raise ValueError: If C{oldChild} is not a child of this C{Node}.
  215. """
  216. if not isinstance(newChild, Node) or not isinstance(oldChild, Node):
  217. raise TypeError("expected Node instance")
  218. if oldChild.parentNode is not self:
  219. raise ValueError("oldChild is not a child of this node")
  220. self.childNodes[self.childNodes.index(oldChild)] = newChild
  221. oldChild.parentNode = None
  222. newChild.parentNode = self
  223. def lastChild(self):
  224. return self.childNodes[-1]
  225. def firstChild(self):
  226. if len(self.childNodes):
  227. return self.childNodes[0]
  228. return None
  229. # def get_ownerDocument(self):
  230. # """This doesn't really get the owner document; microdom nodes
  231. # don't even have one necessarily. This gets the root node,
  232. # which is usually what you really meant.
  233. # *NOT DOM COMPLIANT.*
  234. # """
  235. # node=self
  236. # while (node.parentNode): node=node.parentNode
  237. # return node
  238. # ownerDocument=node.get_ownerDocument()
  239. # leaving commented for discussion; see also domhelpers.getParents(node)
  240. class Document(Node):
  241. def __init__(self, documentElement=None):
  242. Node.__init__(self)
  243. if documentElement:
  244. self.appendChild(documentElement)
  245. def cloneNode(self, deep=0, parent=None):
  246. d = Document()
  247. d.doctype = self.doctype
  248. if deep:
  249. newEl = self.documentElement.cloneNode(1, self)
  250. else:
  251. newEl = self.documentElement
  252. d.appendChild(newEl)
  253. return d
  254. doctype = None
  255. def isEqualToDocument(self, n):
  256. return (self.doctype == n.doctype) and Node.isEqualToNode(self, n)
  257. isEqualToNode = isEqualToDocument
  258. @property
  259. def documentElement(self):
  260. return self.childNodes[0]
  261. def appendChild(self, child):
  262. """
  263. Make the given L{Node} the I{document element} of this L{Document}.
  264. @param child: The L{Node} to make into this L{Document}'s document
  265. element.
  266. @raise ValueError: If this document already has a document element.
  267. """
  268. if self.childNodes:
  269. raise ValueError("Only one element per document.")
  270. Node.appendChild(self, child)
  271. def writexml(
  272. self,
  273. stream,
  274. indent="",
  275. addindent="",
  276. newl="",
  277. strip=0,
  278. nsprefixes={},
  279. namespace="",
  280. ):
  281. w = _streamWriteWrapper(stream)
  282. w('<?xml version="1.0"?>' + newl)
  283. if self.doctype:
  284. w(f"<!DOCTYPE {self.doctype}>{newl}")
  285. self.documentElement.writexml(
  286. stream, indent, addindent, newl, strip, nsprefixes, namespace
  287. )
  288. # of dubious utility (?)
  289. def createElement(self, name, **kw):
  290. return Element(name, **kw)
  291. def createTextNode(self, text):
  292. return Text(text)
  293. def createComment(self, text):
  294. return Comment(text)
  295. def getElementsByTagName(self, name):
  296. if self.documentElement.caseInsensitive:
  297. return getElementsByTagNameNoCase(self, name)
  298. return getElementsByTagName(self, name)
  299. def getElementById(self, id):
  300. childNodes = self.childNodes[:]
  301. while childNodes:
  302. node = childNodes.pop(0)
  303. if node.childNodes:
  304. childNodes.extend(node.childNodes)
  305. if hasattr(node, "getAttribute") and node.getAttribute("id") == id:
  306. return node
  307. class EntityReference(Node):
  308. def __init__(self, eref, parentNode=None):
  309. Node.__init__(self, parentNode)
  310. self.eref = eref
  311. self.nodeValue = self.data = "&" + eref + ";"
  312. def isEqualToEntityReference(self, n):
  313. if not isinstance(n, EntityReference):
  314. return 0
  315. return (self.eref == n.eref) and (self.nodeValue == n.nodeValue)
  316. isEqualToNode = isEqualToEntityReference
  317. def writexml(
  318. self,
  319. stream,
  320. indent="",
  321. addindent="",
  322. newl="",
  323. strip=0,
  324. nsprefixes={},
  325. namespace="",
  326. ):
  327. w = _streamWriteWrapper(stream)
  328. w("" + self.nodeValue)
  329. def cloneNode(self, deep=0, parent=None):
  330. return EntityReference(self.eref, parent)
  331. class CharacterData(Node):
  332. def __init__(self, data, parentNode=None):
  333. Node.__init__(self, parentNode)
  334. self.value = self.data = self.nodeValue = data
  335. def isEqualToCharacterData(self, n):
  336. return self.value == n.value
  337. isEqualToNode = isEqualToCharacterData
  338. class Comment(CharacterData):
  339. """
  340. A comment node.
  341. """
  342. def writexml(
  343. self,
  344. stream,
  345. indent="",
  346. addindent="",
  347. newl="",
  348. strip=0,
  349. nsprefixes={},
  350. namespace="",
  351. ):
  352. w = _streamWriteWrapper(stream)
  353. val = self.data
  354. w(f"<!--{val}-->")
  355. def cloneNode(self, deep=0, parent=None):
  356. return Comment(self.nodeValue, parent)
  357. class Text(CharacterData):
  358. def __init__(self, data, parentNode=None, raw=0):
  359. CharacterData.__init__(self, data, parentNode)
  360. self.raw = raw
  361. def isEqualToNode(self, other):
  362. """
  363. Compare this text to C{text}. If the underlying values and the C{raw}
  364. flag are the same, return C{True}, otherwise return C{False}.
  365. """
  366. return CharacterData.isEqualToNode(self, other) and self.raw == other.raw
  367. def cloneNode(self, deep=0, parent=None):
  368. return Text(self.nodeValue, parent, self.raw)
  369. def writexml(
  370. self,
  371. stream,
  372. indent="",
  373. addindent="",
  374. newl="",
  375. strip=0,
  376. nsprefixes={},
  377. namespace="",
  378. ):
  379. w = _streamWriteWrapper(stream)
  380. if self.raw:
  381. val = self.nodeValue
  382. if not isinstance(val, str):
  383. val = str(self.nodeValue)
  384. else:
  385. v = self.nodeValue
  386. if not isinstance(v, str):
  387. v = str(v)
  388. if strip:
  389. v = " ".join(v.split())
  390. val = escape(v)
  391. w(val)
  392. def __repr__(self) -> str:
  393. return "Text(%s" % repr(self.nodeValue) + ")"
  394. class CDATASection(CharacterData):
  395. def cloneNode(self, deep=0, parent=None):
  396. return CDATASection(self.nodeValue, parent)
  397. def writexml(
  398. self,
  399. stream,
  400. indent="",
  401. addindent="",
  402. newl="",
  403. strip=0,
  404. nsprefixes={},
  405. namespace="",
  406. ):
  407. w = _streamWriteWrapper(stream)
  408. w("<![CDATA[")
  409. w("" + self.nodeValue)
  410. w("]]>")
  411. def _genprefix():
  412. i = 0
  413. while True:
  414. yield "p" + str(i)
  415. i = i + 1
  416. genprefix = _genprefix()
  417. class _Attr(CharacterData):
  418. "Support class for getAttributeNode."
  419. class Element(Node):
  420. preserveCase = 0
  421. caseInsensitive = 1
  422. nsprefixes = None
  423. def __init__(
  424. self,
  425. tagName,
  426. attributes=None,
  427. parentNode=None,
  428. filename=None,
  429. markpos=None,
  430. caseInsensitive=1,
  431. preserveCase=0,
  432. namespace=None,
  433. ):
  434. Node.__init__(self, parentNode)
  435. self.preserveCase = preserveCase or not caseInsensitive
  436. self.caseInsensitive = caseInsensitive
  437. if not preserveCase:
  438. tagName = tagName.lower()
  439. if attributes is None:
  440. self.attributes = {}
  441. else:
  442. self.attributes = attributes
  443. for k, v in self.attributes.items():
  444. self.attributes[k] = unescape(v)
  445. if caseInsensitive:
  446. self.attributes = InsensitiveDict(self.attributes, preserve=preserveCase)
  447. self.endTagName = self.nodeName = self.tagName = tagName
  448. self._filename = filename
  449. self._markpos = markpos
  450. self.namespace = namespace
  451. def addPrefixes(self, pfxs):
  452. if self.nsprefixes is None:
  453. self.nsprefixes = pfxs
  454. else:
  455. self.nsprefixes.update(pfxs)
  456. def endTag(self, endTagName):
  457. if not self.preserveCase:
  458. endTagName = endTagName.lower()
  459. self.endTagName = endTagName
  460. def isEqualToElement(self, n):
  461. if self.caseInsensitive:
  462. return (self.attributes == n.attributes) and (
  463. self.nodeName.lower() == n.nodeName.lower()
  464. )
  465. return (self.attributes == n.attributes) and (self.nodeName == n.nodeName)
  466. def isEqualToNode(self, other):
  467. """
  468. Compare this element to C{other}. If the C{nodeName}, C{namespace},
  469. C{attributes}, and C{childNodes} are all the same, return C{True},
  470. otherwise return C{False}.
  471. """
  472. return (
  473. self.nodeName.lower() == other.nodeName.lower()
  474. and self.namespace == other.namespace
  475. and self.attributes == other.attributes
  476. and Node.isEqualToNode(self, other)
  477. )
  478. def cloneNode(self, deep=0, parent=None):
  479. clone = Element(
  480. self.tagName,
  481. parentNode=parent,
  482. namespace=self.namespace,
  483. preserveCase=self.preserveCase,
  484. caseInsensitive=self.caseInsensitive,
  485. )
  486. clone.attributes.update(self.attributes)
  487. if deep:
  488. clone.childNodes = [child.cloneNode(1, clone) for child in self.childNodes]
  489. else:
  490. clone.childNodes = []
  491. return clone
  492. def getElementsByTagName(self, name):
  493. if self.caseInsensitive:
  494. return getElementsByTagNameNoCase(self, name)
  495. return getElementsByTagName(self, name)
  496. def hasAttributes(self):
  497. return 1
  498. def getAttribute(self, name, default=None):
  499. return self.attributes.get(name, default)
  500. def getAttributeNS(self, ns, name, default=None):
  501. nsk = (ns, name)
  502. if nsk in self.attributes:
  503. return self.attributes[nsk]
  504. if ns == self.namespace:
  505. return self.attributes.get(name, default)
  506. return default
  507. def getAttributeNode(self, name):
  508. return _Attr(self.getAttribute(name), self)
  509. def setAttribute(self, name, attr):
  510. self.attributes[name] = attr
  511. def removeAttribute(self, name):
  512. if name in self.attributes:
  513. del self.attributes[name]
  514. def hasAttribute(self, name):
  515. return name in self.attributes
  516. def writexml(
  517. self,
  518. stream,
  519. indent="",
  520. addindent="",
  521. newl="",
  522. strip=0,
  523. nsprefixes={},
  524. namespace="",
  525. ):
  526. """
  527. Serialize this L{Element} to the given stream.
  528. @param stream: A file-like object to which this L{Element} will be
  529. written.
  530. @param nsprefixes: A C{dict} mapping namespace URIs as C{str} to
  531. prefixes as C{str}. This defines the prefixes which are already in
  532. scope in the document at the point at which this L{Element} exists.
  533. This is essentially an implementation detail for namespace support.
  534. Applications should not try to use it.
  535. @param namespace: The namespace URI as a C{str} which is the default at
  536. the point in the document at which this L{Element} exists. This is
  537. essentially an implementation detail for namespace support.
  538. Applications should not try to use it.
  539. """
  540. # write beginning
  541. ALLOWSINGLETON = (
  542. "img",
  543. "br",
  544. "hr",
  545. "base",
  546. "meta",
  547. "link",
  548. "param",
  549. "area",
  550. "input",
  551. "col",
  552. "basefont",
  553. "isindex",
  554. "frame",
  555. )
  556. BLOCKELEMENTS = (
  557. "html",
  558. "head",
  559. "body",
  560. "noscript",
  561. "ins",
  562. "del",
  563. "h1",
  564. "h2",
  565. "h3",
  566. "h4",
  567. "h5",
  568. "h6",
  569. "script",
  570. "ul",
  571. "ol",
  572. "dl",
  573. "pre",
  574. "hr",
  575. "blockquote",
  576. "address",
  577. "p",
  578. "div",
  579. "fieldset",
  580. "table",
  581. "tr",
  582. "form",
  583. "object",
  584. "fieldset",
  585. "applet",
  586. "map",
  587. )
  588. FORMATNICELY = ("tr", "ul", "ol", "head")
  589. # this should never be necessary unless people start
  590. # changing .tagName on the fly(?)
  591. if not self.preserveCase:
  592. self.endTagName = self.tagName
  593. w = _streamWriteWrapper(stream)
  594. if self.nsprefixes:
  595. newprefixes = self.nsprefixes.copy()
  596. for ns in nsprefixes.keys():
  597. if ns in newprefixes:
  598. del newprefixes[ns]
  599. else:
  600. newprefixes = {}
  601. begin = ["<"]
  602. if self.tagName in BLOCKELEMENTS:
  603. begin = [newl, indent] + begin
  604. bext = begin.extend
  605. writeattr = lambda _atr, _val: bext((" ", _atr, '="', escape(_val), '"'))
  606. # Make a local for tracking what end tag will be used. If namespace
  607. # prefixes are involved, this will be changed to account for that
  608. # before it's actually used.
  609. endTagName = self.endTagName
  610. if namespace != self.namespace and self.namespace is not None:
  611. # If the current default namespace is not the namespace of this tag
  612. # (and this tag has a namespace at all) then we'll write out
  613. # something related to namespaces.
  614. if self.namespace in nsprefixes:
  615. # This tag's namespace already has a prefix bound to it. Use
  616. # that prefix.
  617. prefix = nsprefixes[self.namespace]
  618. bext(prefix + ":" + self.tagName)
  619. # Also make sure we use it for the end tag.
  620. endTagName = prefix + ":" + self.endTagName
  621. else:
  622. # This tag's namespace has no prefix bound to it. Change the
  623. # default namespace to this tag's namespace so we don't need
  624. # prefixes. Alternatively, we could add a new prefix binding.
  625. # I'm not sure why the code was written one way rather than the
  626. # other. -exarkun
  627. bext(self.tagName)
  628. writeattr("xmlns", self.namespace)
  629. # The default namespace just changed. Make sure any children
  630. # know about this.
  631. namespace = self.namespace
  632. else:
  633. # This tag has no namespace or its namespace is already the default
  634. # namespace. Nothing extra to do here.
  635. bext(self.tagName)
  636. j = "".join
  637. for attr, val in sorted(self.attributes.items()):
  638. if isinstance(attr, tuple):
  639. ns, key = attr
  640. if ns in nsprefixes:
  641. prefix = nsprefixes[ns]
  642. else:
  643. prefix = next(genprefix)
  644. newprefixes[ns] = prefix
  645. assert val is not None
  646. writeattr(prefix + ":" + key, val)
  647. else:
  648. assert val is not None
  649. writeattr(attr, val)
  650. if newprefixes:
  651. for ns, prefix in newprefixes.items():
  652. if prefix:
  653. writeattr("xmlns:" + prefix, ns)
  654. newprefixes.update(nsprefixes)
  655. downprefixes = newprefixes
  656. else:
  657. downprefixes = nsprefixes
  658. w(j(begin))
  659. if self.childNodes:
  660. w(">")
  661. newindent = indent + addindent
  662. for child in self.childNodes:
  663. if self.tagName in BLOCKELEMENTS and self.tagName in FORMATNICELY:
  664. w(j((newl, newindent)))
  665. child.writexml(
  666. stream, newindent, addindent, newl, strip, downprefixes, namespace
  667. )
  668. if self.tagName in BLOCKELEMENTS:
  669. w(j((newl, indent)))
  670. w(j(("</", endTagName, ">")))
  671. elif self.tagName.lower() not in ALLOWSINGLETON:
  672. w(j(("></", endTagName, ">")))
  673. else:
  674. w(" />")
  675. def __repr__(self) -> str:
  676. rep = "Element(%s" % repr(self.nodeName)
  677. if self.attributes:
  678. rep += f", attributes={self.attributes!r}"
  679. if self._filename:
  680. rep += f", filename={self._filename!r}"
  681. if self._markpos:
  682. rep += f", markpos={self._markpos!r}"
  683. return rep + ")"
  684. def __str__(self) -> str:
  685. rep = "<" + self.nodeName
  686. if self._filename or self._markpos:
  687. rep += " ("
  688. if self._filename:
  689. rep += repr(self._filename)
  690. if self._markpos:
  691. rep += " line %s column %s" % self._markpos
  692. if self._filename or self._markpos:
  693. rep += ")"
  694. for item in self.attributes.items():
  695. rep += " %s=%r" % item
  696. if self.hasChildNodes():
  697. rep += " >...</%s>" % self.nodeName
  698. else:
  699. rep += " />"
  700. return rep
  701. def _unescapeDict(d):
  702. dd = {}
  703. for k, v in d.items():
  704. dd[k] = unescape(v)
  705. return dd
  706. def _reverseDict(d):
  707. dd = {}
  708. for k, v in d.items():
  709. dd[v] = k
  710. return dd
  711. class MicroDOMParser(XMLParser):
  712. # <dash> glyph: a quick scan thru the DTD says BODY, AREA, LINK, IMG, HR,
  713. # P, DT, DD, LI, INPUT, OPTION, THEAD, TFOOT, TBODY, COLGROUP, COL, TR, TH,
  714. # TD, HEAD, BASE, META, HTML all have optional closing tags
  715. soonClosers = "area link br img hr input base meta".split()
  716. laterClosers = {
  717. "p": ["p", "dt"],
  718. "dt": ["dt", "dd"],
  719. "dd": ["dt", "dd"],
  720. "li": ["li"],
  721. "tbody": ["thead", "tfoot", "tbody"],
  722. "thead": ["thead", "tfoot", "tbody"],
  723. "tfoot": ["thead", "tfoot", "tbody"],
  724. "colgroup": ["colgroup"],
  725. "col": ["col"],
  726. "tr": ["tr"],
  727. "td": ["td"],
  728. "th": ["th"],
  729. "head": ["body"],
  730. "title": ["head", "body"], # this looks wrong...
  731. "option": ["option"],
  732. }
  733. def __init__(
  734. self,
  735. beExtremelyLenient=0,
  736. caseInsensitive=1,
  737. preserveCase=0,
  738. soonClosers=soonClosers,
  739. laterClosers=laterClosers,
  740. ):
  741. self.elementstack = []
  742. d = {"xmlns": "xmlns", "": None}
  743. dr = _reverseDict(d)
  744. self.nsstack = [(d, None, dr)]
  745. self.documents = []
  746. self._mddoctype = None
  747. self.beExtremelyLenient = beExtremelyLenient
  748. self.caseInsensitive = caseInsensitive
  749. self.preserveCase = preserveCase or not caseInsensitive
  750. self.soonClosers = soonClosers
  751. self.laterClosers = laterClosers
  752. # self.indentlevel = 0
  753. def shouldPreserveSpace(self):
  754. for edx in range(len(self.elementstack)):
  755. el = self.elementstack[-edx]
  756. if el.tagName == "pre" or el.getAttribute("xml:space", "") == "preserve":
  757. return 1
  758. return 0
  759. def _getparent(self):
  760. if self.elementstack:
  761. return self.elementstack[-1]
  762. else:
  763. return None
  764. COMMENT = re.compile(r"\s*/[/*]\s*")
  765. def _fixScriptElement(self, el):
  766. # this deals with case where there is comment or CDATA inside
  767. # <script> tag and we want to do the right thing with it
  768. if not self.beExtremelyLenient or not len(el.childNodes) == 1:
  769. return
  770. c = el.firstChild()
  771. if isinstance(c, Text):
  772. # deal with nasty people who do stuff like:
  773. # <script> // <!--
  774. # x = 1;
  775. # // --></script>
  776. # tidy does this, for example.
  777. prefix = ""
  778. oldvalue = c.value
  779. match = self.COMMENT.match(oldvalue)
  780. if match:
  781. prefix = match.group()
  782. oldvalue = oldvalue[len(prefix) :]
  783. # now see if contents are actual node and comment or CDATA
  784. try:
  785. e = parseString("<a>%s</a>" % oldvalue).childNodes[0]
  786. except (ParseError, MismatchedTags):
  787. return
  788. if len(e.childNodes) != 1:
  789. return
  790. e = e.firstChild()
  791. if isinstance(e, (CDATASection, Comment)):
  792. el.childNodes = []
  793. if prefix:
  794. el.childNodes.append(Text(prefix))
  795. el.childNodes.append(e)
  796. def gotDoctype(self, doctype):
  797. self._mddoctype = doctype
  798. def gotTagStart(self, name, attributes):
  799. # print ' '*self.indentlevel, 'start tag',name
  800. # self.indentlevel += 1
  801. parent = self._getparent()
  802. if self.beExtremelyLenient and isinstance(parent, Element):
  803. parentName = parent.tagName
  804. myName = name
  805. if self.caseInsensitive:
  806. parentName = parentName.lower()
  807. myName = myName.lower()
  808. if myName in self.laterClosers.get(parentName, []):
  809. self.gotTagEnd(parent.tagName)
  810. parent = self._getparent()
  811. attributes = _unescapeDict(attributes)
  812. namespaces = self.nsstack[-1][0]
  813. newspaces = {}
  814. keysToDelete = []
  815. for k, v in attributes.items():
  816. if k.startswith("xmlns"):
  817. spacenames = k.split(":", 1)
  818. if len(spacenames) == 2:
  819. newspaces[spacenames[1]] = v
  820. else:
  821. newspaces[""] = v
  822. keysToDelete.append(k)
  823. for k in keysToDelete:
  824. del attributes[k]
  825. if newspaces:
  826. namespaces = namespaces.copy()
  827. namespaces.update(newspaces)
  828. keysToDelete = []
  829. for k, v in attributes.items():
  830. ksplit = k.split(":", 1)
  831. if len(ksplit) == 2:
  832. pfx, tv = ksplit
  833. if pfx != "xml" and pfx in namespaces:
  834. attributes[namespaces[pfx], tv] = v
  835. keysToDelete.append(k)
  836. for k in keysToDelete:
  837. del attributes[k]
  838. el = Element(
  839. name,
  840. attributes,
  841. parent,
  842. self.filename,
  843. self.saveMark(),
  844. caseInsensitive=self.caseInsensitive,
  845. preserveCase=self.preserveCase,
  846. namespace=namespaces.get(""),
  847. )
  848. revspaces = _reverseDict(newspaces)
  849. el.addPrefixes(revspaces)
  850. if newspaces:
  851. rscopy = self.nsstack[-1][2].copy()
  852. rscopy.update(revspaces)
  853. self.nsstack.append((namespaces, el, rscopy))
  854. self.elementstack.append(el)
  855. if parent:
  856. parent.appendChild(el)
  857. if self.beExtremelyLenient and el.tagName in self.soonClosers:
  858. self.gotTagEnd(name)
  859. def _gotStandalone(self, factory, data):
  860. parent = self._getparent()
  861. te = factory(data, parent)
  862. if parent:
  863. parent.appendChild(te)
  864. elif self.beExtremelyLenient:
  865. self.documents.append(te)
  866. def gotText(self, data):
  867. if data.strip() or self.shouldPreserveSpace():
  868. self._gotStandalone(Text, data)
  869. def gotComment(self, data):
  870. self._gotStandalone(Comment, data)
  871. def gotEntityReference(self, entityRef):
  872. self._gotStandalone(EntityReference, entityRef)
  873. def gotCData(self, cdata):
  874. self._gotStandalone(CDATASection, cdata)
  875. def gotTagEnd(self, name):
  876. # print ' '*self.indentlevel, 'end tag',name
  877. # self.indentlevel -= 1
  878. if not self.elementstack:
  879. if self.beExtremelyLenient:
  880. return
  881. raise MismatchedTags(
  882. *((self.filename, "NOTHING", name) + self.saveMark() + (0, 0))
  883. )
  884. el = self.elementstack.pop()
  885. pfxdix = self.nsstack[-1][2]
  886. if self.nsstack[-1][1] is el:
  887. nstuple = self.nsstack.pop()
  888. else:
  889. nstuple = None
  890. if self.caseInsensitive:
  891. tn = el.tagName.lower()
  892. cname = name.lower()
  893. else:
  894. tn = el.tagName
  895. cname = name
  896. nsplit = name.split(":", 1)
  897. if len(nsplit) == 2:
  898. pfx, newname = nsplit
  899. ns = pfxdix.get(pfx, None)
  900. if ns is not None:
  901. if el.namespace != ns:
  902. if not self.beExtremelyLenient:
  903. raise MismatchedTags(
  904. *(
  905. (self.filename, el.tagName, name)
  906. + self.saveMark()
  907. + el._markpos
  908. )
  909. )
  910. if not (tn == cname):
  911. if self.beExtremelyLenient:
  912. if self.elementstack:
  913. lastEl = self.elementstack[0]
  914. for idx in range(len(self.elementstack)):
  915. if self.elementstack[-(idx + 1)].tagName == cname:
  916. self.elementstack[-(idx + 1)].endTag(name)
  917. break
  918. else:
  919. # this was a garbage close tag; wait for a real one
  920. self.elementstack.append(el)
  921. if nstuple is not None:
  922. self.nsstack.append(nstuple)
  923. return
  924. del self.elementstack[-(idx + 1) :]
  925. if not self.elementstack:
  926. self.documents.append(lastEl)
  927. return
  928. else:
  929. raise MismatchedTags(
  930. *((self.filename, el.tagName, name) + self.saveMark() + el._markpos)
  931. )
  932. el.endTag(name)
  933. if not self.elementstack:
  934. self.documents.append(el)
  935. if self.beExtremelyLenient and el.tagName == "script":
  936. self._fixScriptElement(el)
  937. def connectionLost(self, reason):
  938. XMLParser.connectionLost(self, reason) # This can cause more events!
  939. if self.elementstack:
  940. if self.beExtremelyLenient:
  941. self.documents.append(self.elementstack[0])
  942. else:
  943. raise MismatchedTags(
  944. *(
  945. (self.filename, self.elementstack[-1], "END_OF_FILE")
  946. + self.saveMark()
  947. + self.elementstack[-1]._markpos
  948. )
  949. )
  950. def parse(readable, *args, **kwargs):
  951. """
  952. Parse HTML or XML readable.
  953. """
  954. if not hasattr(readable, "read"):
  955. readable = open(readable, "rb")
  956. mdp = MicroDOMParser(*args, **kwargs)
  957. mdp.filename = getattr(readable, "name", "<xmlfile />")
  958. mdp.makeConnection(None)
  959. if hasattr(readable, "getvalue"):
  960. mdp.dataReceived(readable.getvalue())
  961. else:
  962. r = readable.read(1024)
  963. while r:
  964. mdp.dataReceived(r)
  965. r = readable.read(1024)
  966. mdp.connectionLost(None)
  967. if not mdp.documents:
  968. raise ParseError(mdp.filename, 0, 0, "No top-level Nodes in document")
  969. if mdp.beExtremelyLenient:
  970. if len(mdp.documents) == 1:
  971. d = mdp.documents[0]
  972. if not isinstance(d, Element):
  973. el = Element("html")
  974. el.appendChild(d)
  975. d = el
  976. else:
  977. d = Element("html")
  978. for child in mdp.documents:
  979. d.appendChild(child)
  980. else:
  981. d = mdp.documents[0]
  982. doc = Document(d)
  983. doc.doctype = mdp._mddoctype
  984. return doc
  985. def parseString(st, *args, **kw):
  986. if isinstance(st, str):
  987. # this isn't particularly ideal, but it does work.
  988. return parse(BytesIO(st.encode("UTF-16")), *args, **kw)
  989. return parse(BytesIO(st), *args, **kw)
  990. def parseXML(readable):
  991. """
  992. Parse an XML readable object.
  993. """
  994. return parse(readable, caseInsensitive=0, preserveCase=1)
  995. def parseXMLString(st):
  996. """
  997. Parse an XML readable object.
  998. """
  999. return parseString(st, caseInsensitive=0, preserveCase=1)
  1000. class lmx:
  1001. """
  1002. Easy creation of XML.
  1003. """
  1004. def __init__(self, node="div"):
  1005. if isinstance(node, str):
  1006. node = Element(node)
  1007. self.node = node
  1008. def __getattr__(self, name):
  1009. if name[0] == "_":
  1010. raise AttributeError("no private attrs")
  1011. return lambda **kw: self.add(name, **kw)
  1012. def __setitem__(self, key, val):
  1013. self.node.setAttribute(key, val)
  1014. def __getitem__(self, key):
  1015. return self.node.getAttribute(key)
  1016. def text(self, txt, raw=0):
  1017. nn = Text(txt, raw=raw)
  1018. self.node.appendChild(nn)
  1019. return self
  1020. def add(self, tagName, **kw):
  1021. newNode = Element(tagName, caseInsensitive=0, preserveCase=0)
  1022. self.node.appendChild(newNode)
  1023. xf = lmx(newNode)
  1024. for k, v in kw.items():
  1025. if k[0] == "_":
  1026. k = k[1:]
  1027. xf[k] = v
  1028. return xf