microdom.py 36 KB

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