microdom.py 35 KB

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