microdom.py 35 KB

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