PageRenderTime 81ms CodeModel.GetById 32ms RepoModel.GetById 1ms app.codeStats 1ms

/lib-python/2.7/xmllib.py

https://bitbucket.org/mpavone/pypy
Python | 930 lines | 851 code | 37 blank | 42 comment | 147 complexity | b73135f8ee0eca6c1f2d43863b4b16a9 MD5 | raw file
  1. """A parser for XML, using the derived class as static DTD."""
  2. # Author: Sjoerd Mullender.
  3. import re
  4. import string
  5. import warnings
  6. warnings.warn("The xmllib module is obsolete. Use xml.sax instead.",
  7. DeprecationWarning, 2)
  8. del warnings
  9. version = '0.3'
  10. class Error(RuntimeError):
  11. pass
  12. # Regular expressions used for parsing
  13. _S = '[ \t\r\n]+' # white space
  14. _opS = '[ \t\r\n]*' # optional white space
  15. _Name = '[a-zA-Z_:][-a-zA-Z0-9._:]*' # valid XML name
  16. _QStr = "(?:'[^']*'|\"[^\"]*\")" # quoted XML string
  17. illegal = re.compile('[^\t\r\n -\176\240-\377]') # illegal chars in content
  18. interesting = re.compile('[]&<]')
  19. amp = re.compile('&')
  20. ref = re.compile('&(' + _Name + '|#[0-9]+|#x[0-9a-fA-F]+)[^-a-zA-Z0-9._:]')
  21. entityref = re.compile('&(?P<name>' + _Name + ')[^-a-zA-Z0-9._:]')
  22. charref = re.compile('&#(?P<char>[0-9]+[^0-9]|x[0-9a-fA-F]+[^0-9a-fA-F])')
  23. space = re.compile(_S + '$')
  24. newline = re.compile('\n')
  25. attrfind = re.compile(
  26. _S + '(?P<name>' + _Name + ')'
  27. '(' + _opS + '=' + _opS +
  28. '(?P<value>'+_QStr+'|[-a-zA-Z0-9.:+*%?!\(\)_#=~]+))?')
  29. starttagopen = re.compile('<' + _Name)
  30. starttagend = re.compile(_opS + '(?P<slash>/?)>')
  31. starttagmatch = re.compile('<(?P<tagname>'+_Name+')'
  32. '(?P<attrs>(?:'+attrfind.pattern+')*)'+
  33. starttagend.pattern)
  34. endtagopen = re.compile('</')
  35. endbracket = re.compile(_opS + '>')
  36. endbracketfind = re.compile('(?:[^>\'"]|'+_QStr+')*>')
  37. tagfind = re.compile(_Name)
  38. cdataopen = re.compile(r'<!\[CDATA\[')
  39. cdataclose = re.compile(r'\]\]>')
  40. # this matches one of the following:
  41. # SYSTEM SystemLiteral
  42. # PUBLIC PubidLiteral SystemLiteral
  43. _SystemLiteral = '(?P<%s>'+_QStr+')'
  44. _PublicLiteral = '(?P<%s>"[-\'\(\)+,./:=?;!*#@$_%% \n\ra-zA-Z0-9]*"|' \
  45. "'[-\(\)+,./:=?;!*#@$_%% \n\ra-zA-Z0-9]*')"
  46. _ExternalId = '(?:SYSTEM|' \
  47. 'PUBLIC'+_S+_PublicLiteral%'pubid'+ \
  48. ')'+_S+_SystemLiteral%'syslit'
  49. doctype = re.compile('<!DOCTYPE'+_S+'(?P<name>'+_Name+')'
  50. '(?:'+_S+_ExternalId+')?'+_opS)
  51. xmldecl = re.compile('<\?xml'+_S+
  52. 'version'+_opS+'='+_opS+'(?P<version>'+_QStr+')'+
  53. '(?:'+_S+'encoding'+_opS+'='+_opS+
  54. "(?P<encoding>'[A-Za-z][-A-Za-z0-9._]*'|"
  55. '"[A-Za-z][-A-Za-z0-9._]*"))?'
  56. '(?:'+_S+'standalone'+_opS+'='+_opS+
  57. '(?P<standalone>\'(?:yes|no)\'|"(?:yes|no)"))?'+
  58. _opS+'\?>')
  59. procopen = re.compile(r'<\?(?P<proc>' + _Name + ')' + _opS)
  60. procclose = re.compile(_opS + r'\?>')
  61. commentopen = re.compile('<!--')
  62. commentclose = re.compile('-->')
  63. doubledash = re.compile('--')
  64. attrtrans = string.maketrans(' \r\n\t', ' ')
  65. # definitions for XML namespaces
  66. _NCName = '[a-zA-Z_][-a-zA-Z0-9._]*' # XML Name, minus the ":"
  67. ncname = re.compile(_NCName + '$')
  68. qname = re.compile('(?:(?P<prefix>' + _NCName + '):)?' # optional prefix
  69. '(?P<local>' + _NCName + ')$')
  70. xmlns = re.compile('xmlns(?::(?P<ncname>'+_NCName+'))?$')
  71. # XML parser base class -- find tags and call handler functions.
  72. # Usage: p = XMLParser(); p.feed(data); ...; p.close().
  73. # The dtd is defined by deriving a class which defines methods with
  74. # special names to handle tags: start_foo and end_foo to handle <foo>
  75. # and </foo>, respectively. The data between tags is passed to the
  76. # parser by calling self.handle_data() with some data as argument (the
  77. # data may be split up in arbitrary chunks).
  78. class XMLParser:
  79. attributes = {} # default, to be overridden
  80. elements = {} # default, to be overridden
  81. # parsing options, settable using keyword args in __init__
  82. __accept_unquoted_attributes = 0
  83. __accept_missing_endtag_name = 0
  84. __map_case = 0
  85. __accept_utf8 = 0
  86. __translate_attribute_references = 1
  87. # Interface -- initialize and reset this instance
  88. def __init__(self, **kw):
  89. self.__fixed = 0
  90. if 'accept_unquoted_attributes' in kw:
  91. self.__accept_unquoted_attributes = kw['accept_unquoted_attributes']
  92. if 'accept_missing_endtag_name' in kw:
  93. self.__accept_missing_endtag_name = kw['accept_missing_endtag_name']
  94. if 'map_case' in kw:
  95. self.__map_case = kw['map_case']
  96. if 'accept_utf8' in kw:
  97. self.__accept_utf8 = kw['accept_utf8']
  98. if 'translate_attribute_references' in kw:
  99. self.__translate_attribute_references = kw['translate_attribute_references']
  100. self.reset()
  101. def __fixelements(self):
  102. self.__fixed = 1
  103. self.elements = {}
  104. self.__fixdict(self.__dict__)
  105. self.__fixclass(self.__class__)
  106. def __fixclass(self, kl):
  107. self.__fixdict(kl.__dict__)
  108. for k in kl.__bases__:
  109. self.__fixclass(k)
  110. def __fixdict(self, dict):
  111. for key in dict.keys():
  112. if key[:6] == 'start_':
  113. tag = key[6:]
  114. start, end = self.elements.get(tag, (None, None))
  115. if start is None:
  116. self.elements[tag] = getattr(self, key), end
  117. elif key[:4] == 'end_':
  118. tag = key[4:]
  119. start, end = self.elements.get(tag, (None, None))
  120. if end is None:
  121. self.elements[tag] = start, getattr(self, key)
  122. # Interface -- reset this instance. Loses all unprocessed data
  123. def reset(self):
  124. self.rawdata = ''
  125. self.stack = []
  126. self.nomoretags = 0
  127. self.literal = 0
  128. self.lineno = 1
  129. self.__at_start = 1
  130. self.__seen_doctype = None
  131. self.__seen_starttag = 0
  132. self.__use_namespaces = 0
  133. self.__namespaces = {'xml':None} # xml is implicitly declared
  134. # backward compatibility hack: if elements not overridden,
  135. # fill it in ourselves
  136. if self.elements is XMLParser.elements:
  137. self.__fixelements()
  138. # For derived classes only -- enter literal mode (CDATA) till EOF
  139. def setnomoretags(self):
  140. self.nomoretags = self.literal = 1
  141. # For derived classes only -- enter literal mode (CDATA)
  142. def setliteral(self, *args):
  143. self.literal = 1
  144. # Interface -- feed some data to the parser. Call this as
  145. # often as you want, with as little or as much text as you
  146. # want (may include '\n'). (This just saves the text, all the
  147. # processing is done by goahead().)
  148. def feed(self, data):
  149. self.rawdata = self.rawdata + data
  150. self.goahead(0)
  151. # Interface -- handle the remaining data
  152. def close(self):
  153. self.goahead(1)
  154. if self.__fixed:
  155. self.__fixed = 0
  156. # remove self.elements so that we don't leak
  157. del self.elements
  158. # Interface -- translate references
  159. def translate_references(self, data, all = 1):
  160. if not self.__translate_attribute_references:
  161. return data
  162. i = 0
  163. while 1:
  164. res = amp.search(data, i)
  165. if res is None:
  166. return data
  167. s = res.start(0)
  168. res = ref.match(data, s)
  169. if res is None:
  170. self.syntax_error("bogus `&'")
  171. i = s+1
  172. continue
  173. i = res.end(0)
  174. str = res.group(1)
  175. rescan = 0
  176. if str[0] == '#':
  177. if str[1] == 'x':
  178. str = chr(int(str[2:], 16))
  179. else:
  180. str = chr(int(str[1:]))
  181. if data[i - 1] != ';':
  182. self.syntax_error("`;' missing after char reference")
  183. i = i-1
  184. elif all:
  185. if str in self.entitydefs:
  186. str = self.entitydefs[str]
  187. rescan = 1
  188. elif data[i - 1] != ';':
  189. self.syntax_error("bogus `&'")
  190. i = s + 1 # just past the &
  191. continue
  192. else:
  193. self.syntax_error("reference to unknown entity `&%s;'" % str)
  194. str = '&' + str + ';'
  195. elif data[i - 1] != ';':
  196. self.syntax_error("bogus `&'")
  197. i = s + 1 # just past the &
  198. continue
  199. # when we get here, str contains the translated text and i points
  200. # to the end of the string that is to be replaced
  201. data = data[:s] + str + data[i:]
  202. if rescan:
  203. i = s
  204. else:
  205. i = s + len(str)
  206. # Interface - return a dictionary of all namespaces currently valid
  207. def getnamespace(self):
  208. nsdict = {}
  209. for t, d, nst in self.stack:
  210. nsdict.update(d)
  211. return nsdict
  212. # Internal -- handle data as far as reasonable. May leave state
  213. # and data to be processed by a subsequent call. If 'end' is
  214. # true, force handling all data as if followed by EOF marker.
  215. def goahead(self, end):
  216. rawdata = self.rawdata
  217. i = 0
  218. n = len(rawdata)
  219. while i < n:
  220. if i > 0:
  221. self.__at_start = 0
  222. if self.nomoretags:
  223. data = rawdata[i:n]
  224. self.handle_data(data)
  225. self.lineno = self.lineno + data.count('\n')
  226. i = n
  227. break
  228. res = interesting.search(rawdata, i)
  229. if res:
  230. j = res.start(0)
  231. else:
  232. j = n
  233. if i < j:
  234. data = rawdata[i:j]
  235. if self.__at_start and space.match(data) is None:
  236. self.syntax_error('illegal data at start of file')
  237. self.__at_start = 0
  238. if not self.stack and space.match(data) is None:
  239. self.syntax_error('data not in content')
  240. if not self.__accept_utf8 and illegal.search(data):
  241. self.syntax_error('illegal character in content')
  242. self.handle_data(data)
  243. self.lineno = self.lineno + data.count('\n')
  244. i = j
  245. if i == n: break
  246. if rawdata[i] == '<':
  247. if starttagopen.match(rawdata, i):
  248. if self.literal:
  249. data = rawdata[i]
  250. self.handle_data(data)
  251. self.lineno = self.lineno + data.count('\n')
  252. i = i+1
  253. continue
  254. k = self.parse_starttag(i)
  255. if k < 0: break
  256. self.__seen_starttag = 1
  257. self.lineno = self.lineno + rawdata[i:k].count('\n')
  258. i = k
  259. continue
  260. if endtagopen.match(rawdata, i):
  261. k = self.parse_endtag(i)
  262. if k < 0: break
  263. self.lineno = self.lineno + rawdata[i:k].count('\n')
  264. i = k
  265. continue
  266. if commentopen.match(rawdata, i):
  267. if self.literal:
  268. data = rawdata[i]
  269. self.handle_data(data)
  270. self.lineno = self.lineno + data.count('\n')
  271. i = i+1
  272. continue
  273. k = self.parse_comment(i)
  274. if k < 0: break
  275. self.lineno = self.lineno + rawdata[i:k].count('\n')
  276. i = k
  277. continue
  278. if cdataopen.match(rawdata, i):
  279. k = self.parse_cdata(i)
  280. if k < 0: break
  281. self.lineno = self.lineno + rawdata[i:k].count('\n')
  282. i = k
  283. continue
  284. res = xmldecl.match(rawdata, i)
  285. if res:
  286. if not self.__at_start:
  287. self.syntax_error("<?xml?> declaration not at start of document")
  288. version, encoding, standalone = res.group('version',
  289. 'encoding',
  290. 'standalone')
  291. if version[1:-1] != '1.0':
  292. raise Error('only XML version 1.0 supported')
  293. if encoding: encoding = encoding[1:-1]
  294. if standalone: standalone = standalone[1:-1]
  295. self.handle_xml(encoding, standalone)
  296. i = res.end(0)
  297. continue
  298. res = procopen.match(rawdata, i)
  299. if res:
  300. k = self.parse_proc(i)
  301. if k < 0: break
  302. self.lineno = self.lineno + rawdata[i:k].count('\n')
  303. i = k
  304. continue
  305. res = doctype.match(rawdata, i)
  306. if res:
  307. if self.literal:
  308. data = rawdata[i]
  309. self.handle_data(data)
  310. self.lineno = self.lineno + data.count('\n')
  311. i = i+1
  312. continue
  313. if self.__seen_doctype:
  314. self.syntax_error('multiple DOCTYPE elements')
  315. if self.__seen_starttag:
  316. self.syntax_error('DOCTYPE not at beginning of document')
  317. k = self.parse_doctype(res)
  318. if k < 0: break
  319. self.__seen_doctype = res.group('name')
  320. if self.__map_case:
  321. self.__seen_doctype = self.__seen_doctype.lower()
  322. self.lineno = self.lineno + rawdata[i:k].count('\n')
  323. i = k
  324. continue
  325. elif rawdata[i] == '&':
  326. if self.literal:
  327. data = rawdata[i]
  328. self.handle_data(data)
  329. i = i+1
  330. continue
  331. res = charref.match(rawdata, i)
  332. if res is not None:
  333. i = res.end(0)
  334. if rawdata[i-1] != ';':
  335. self.syntax_error("`;' missing in charref")
  336. i = i-1
  337. if not self.stack:
  338. self.syntax_error('data not in content')
  339. self.handle_charref(res.group('char')[:-1])
  340. self.lineno = self.lineno + res.group(0).count('\n')
  341. continue
  342. res = entityref.match(rawdata, i)
  343. if res is not None:
  344. i = res.end(0)
  345. if rawdata[i-1] != ';':
  346. self.syntax_error("`;' missing in entityref")
  347. i = i-1
  348. name = res.group('name')
  349. if self.__map_case:
  350. name = name.lower()
  351. if name in self.entitydefs:
  352. self.rawdata = rawdata = rawdata[:res.start(0)] + self.entitydefs[name] + rawdata[i:]
  353. n = len(rawdata)
  354. i = res.start(0)
  355. else:
  356. self.unknown_entityref(name)
  357. self.lineno = self.lineno + res.group(0).count('\n')
  358. continue
  359. elif rawdata[i] == ']':
  360. if self.literal:
  361. data = rawdata[i]
  362. self.handle_data(data)
  363. i = i+1
  364. continue
  365. if n-i < 3:
  366. break
  367. if cdataclose.match(rawdata, i):
  368. self.syntax_error("bogus `]]>'")
  369. self.handle_data(rawdata[i])
  370. i = i+1
  371. continue
  372. else:
  373. raise Error('neither < nor & ??')
  374. # We get here only if incomplete matches but
  375. # nothing else
  376. break
  377. # end while
  378. if i > 0:
  379. self.__at_start = 0
  380. if end and i < n:
  381. data = rawdata[i]
  382. self.syntax_error("bogus `%s'" % data)
  383. if not self.__accept_utf8 and illegal.search(data):
  384. self.syntax_error('illegal character in content')
  385. self.handle_data(data)
  386. self.lineno = self.lineno + data.count('\n')
  387. self.rawdata = rawdata[i+1:]
  388. return self.goahead(end)
  389. self.rawdata = rawdata[i:]
  390. if end:
  391. if not self.__seen_starttag:
  392. self.syntax_error('no elements in file')
  393. if self.stack:
  394. self.syntax_error('missing end tags')
  395. while self.stack:
  396. self.finish_endtag(self.stack[-1][0])
  397. # Internal -- parse comment, return length or -1 if not terminated
  398. def parse_comment(self, i):
  399. rawdata = self.rawdata
  400. if rawdata[i:i+4] != '<!--':
  401. raise Error('unexpected call to handle_comment')
  402. res = commentclose.search(rawdata, i+4)
  403. if res is None:
  404. return -1
  405. if doubledash.search(rawdata, i+4, res.start(0)):
  406. self.syntax_error("`--' inside comment")
  407. if rawdata[res.start(0)-1] == '-':
  408. self.syntax_error('comment cannot end in three dashes')
  409. if not self.__accept_utf8 and \
  410. illegal.search(rawdata, i+4, res.start(0)):
  411. self.syntax_error('illegal character in comment')
  412. self.handle_comment(rawdata[i+4: res.start(0)])
  413. return res.end(0)
  414. # Internal -- handle DOCTYPE tag, return length or -1 if not terminated
  415. def parse_doctype(self, res):
  416. rawdata = self.rawdata
  417. n = len(rawdata)
  418. name = res.group('name')
  419. if self.__map_case:
  420. name = name.lower()
  421. pubid, syslit = res.group('pubid', 'syslit')
  422. if pubid is not None:
  423. pubid = pubid[1:-1] # remove quotes
  424. pubid = ' '.join(pubid.split()) # normalize
  425. if syslit is not None: syslit = syslit[1:-1] # remove quotes
  426. j = k = res.end(0)
  427. if k >= n:
  428. return -1
  429. if rawdata[k] == '[':
  430. level = 0
  431. k = k+1
  432. dq = sq = 0
  433. while k < n:
  434. c = rawdata[k]
  435. if not sq and c == '"':
  436. dq = not dq
  437. elif not dq and c == "'":
  438. sq = not sq
  439. elif sq or dq:
  440. pass
  441. elif level <= 0 and c == ']':
  442. res = endbracket.match(rawdata, k+1)
  443. if res is None:
  444. return -1
  445. self.handle_doctype(name, pubid, syslit, rawdata[j+1:k])
  446. return res.end(0)
  447. elif c == '<':
  448. level = level + 1
  449. elif c == '>':
  450. level = level - 1
  451. if level < 0:
  452. self.syntax_error("bogus `>' in DOCTYPE")
  453. k = k+1
  454. res = endbracketfind.match(rawdata, k)
  455. if res is None:
  456. return -1
  457. if endbracket.match(rawdata, k) is None:
  458. self.syntax_error('garbage in DOCTYPE')
  459. self.handle_doctype(name, pubid, syslit, None)
  460. return res.end(0)
  461. # Internal -- handle CDATA tag, return length or -1 if not terminated
  462. def parse_cdata(self, i):
  463. rawdata = self.rawdata
  464. if rawdata[i:i+9] != '<![CDATA[':
  465. raise Error('unexpected call to parse_cdata')
  466. res = cdataclose.search(rawdata, i+9)
  467. if res is None:
  468. return -1
  469. if not self.__accept_utf8 and \
  470. illegal.search(rawdata, i+9, res.start(0)):
  471. self.syntax_error('illegal character in CDATA')
  472. if not self.stack:
  473. self.syntax_error('CDATA not in content')
  474. self.handle_cdata(rawdata[i+9:res.start(0)])
  475. return res.end(0)
  476. __xml_namespace_attributes = {'ns':None, 'src':None, 'prefix':None}
  477. # Internal -- handle a processing instruction tag
  478. def parse_proc(self, i):
  479. rawdata = self.rawdata
  480. end = procclose.search(rawdata, i)
  481. if end is None:
  482. return -1
  483. j = end.start(0)
  484. if not self.__accept_utf8 and illegal.search(rawdata, i+2, j):
  485. self.syntax_error('illegal character in processing instruction')
  486. res = tagfind.match(rawdata, i+2)
  487. if res is None:
  488. raise Error('unexpected call to parse_proc')
  489. k = res.end(0)
  490. name = res.group(0)
  491. if self.__map_case:
  492. name = name.lower()
  493. if name == 'xml:namespace':
  494. self.syntax_error('old-fashioned namespace declaration')
  495. self.__use_namespaces = -1
  496. # namespace declaration
  497. # this must come after the <?xml?> declaration (if any)
  498. # and before the <!DOCTYPE> (if any).
  499. if self.__seen_doctype or self.__seen_starttag:
  500. self.syntax_error('xml:namespace declaration too late in document')
  501. attrdict, namespace, k = self.parse_attributes(name, k, j)
  502. if namespace:
  503. self.syntax_error('namespace declaration inside namespace declaration')
  504. for attrname in attrdict.keys():
  505. if not attrname in self.__xml_namespace_attributes:
  506. self.syntax_error("unknown attribute `%s' in xml:namespace tag" % attrname)
  507. if not 'ns' in attrdict or not 'prefix' in attrdict:
  508. self.syntax_error('xml:namespace without required attributes')
  509. prefix = attrdict.get('prefix')
  510. if ncname.match(prefix) is None:
  511. self.syntax_error('xml:namespace illegal prefix value')
  512. return end.end(0)
  513. if prefix in self.__namespaces:
  514. self.syntax_error('xml:namespace prefix not unique')
  515. self.__namespaces[prefix] = attrdict['ns']
  516. else:
  517. if name.lower() == 'xml':
  518. self.syntax_error('illegal processing instruction target name')
  519. self.handle_proc(name, rawdata[k:j])
  520. return end.end(0)
  521. # Internal -- parse attributes between i and j
  522. def parse_attributes(self, tag, i, j):
  523. rawdata = self.rawdata
  524. attrdict = {}
  525. namespace = {}
  526. while i < j:
  527. res = attrfind.match(rawdata, i)
  528. if res is None:
  529. break
  530. attrname, attrvalue = res.group('name', 'value')
  531. if self.__map_case:
  532. attrname = attrname.lower()
  533. i = res.end(0)
  534. if attrvalue is None:
  535. self.syntax_error("no value specified for attribute `%s'" % attrname)
  536. attrvalue = attrname
  537. elif attrvalue[:1] == "'" == attrvalue[-1:] or \
  538. attrvalue[:1] == '"' == attrvalue[-1:]:
  539. attrvalue = attrvalue[1:-1]
  540. elif not self.__accept_unquoted_attributes:
  541. self.syntax_error("attribute `%s' value not quoted" % attrname)
  542. res = xmlns.match(attrname)
  543. if res is not None:
  544. # namespace declaration
  545. ncname = res.group('ncname')
  546. namespace[ncname or ''] = attrvalue or None
  547. if not self.__use_namespaces:
  548. self.__use_namespaces = len(self.stack)+1
  549. continue
  550. if '<' in attrvalue:
  551. self.syntax_error("`<' illegal in attribute value")
  552. if attrname in attrdict:
  553. self.syntax_error("attribute `%s' specified twice" % attrname)
  554. attrvalue = attrvalue.translate(attrtrans)
  555. attrdict[attrname] = self.translate_references(attrvalue)
  556. return attrdict, namespace, i
  557. # Internal -- handle starttag, return length or -1 if not terminated
  558. def parse_starttag(self, i):
  559. rawdata = self.rawdata
  560. # i points to start of tag
  561. end = endbracketfind.match(rawdata, i+1)
  562. if end is None:
  563. return -1
  564. tag = starttagmatch.match(rawdata, i)
  565. if tag is None or tag.end(0) != end.end(0):
  566. self.syntax_error('garbage in starttag')
  567. return end.end(0)
  568. nstag = tagname = tag.group('tagname')
  569. if self.__map_case:
  570. nstag = tagname = nstag.lower()
  571. if not self.__seen_starttag and self.__seen_doctype and \
  572. tagname != self.__seen_doctype:
  573. self.syntax_error('starttag does not match DOCTYPE')
  574. if self.__seen_starttag and not self.stack:
  575. self.syntax_error('multiple elements on top level')
  576. k, j = tag.span('attrs')
  577. attrdict, nsdict, k = self.parse_attributes(tagname, k, j)
  578. self.stack.append((tagname, nsdict, nstag))
  579. if self.__use_namespaces:
  580. res = qname.match(tagname)
  581. else:
  582. res = None
  583. if res is not None:
  584. prefix, nstag = res.group('prefix', 'local')
  585. if prefix is None:
  586. prefix = ''
  587. ns = None
  588. for t, d, nst in self.stack:
  589. if prefix in d:
  590. ns = d[prefix]
  591. if ns is None and prefix != '':
  592. ns = self.__namespaces.get(prefix)
  593. if ns is not None:
  594. nstag = ns + ' ' + nstag
  595. elif prefix != '':
  596. nstag = prefix + ':' + nstag # undo split
  597. self.stack[-1] = tagname, nsdict, nstag
  598. # translate namespace of attributes
  599. attrnamemap = {} # map from new name to old name (used for error reporting)
  600. for key in attrdict.keys():
  601. attrnamemap[key] = key
  602. if self.__use_namespaces:
  603. nattrdict = {}
  604. for key, val in attrdict.items():
  605. okey = key
  606. res = qname.match(key)
  607. if res is not None:
  608. aprefix, key = res.group('prefix', 'local')
  609. if self.__map_case:
  610. key = key.lower()
  611. if aprefix is not None:
  612. ans = None
  613. for t, d, nst in self.stack:
  614. if aprefix in d:
  615. ans = d[aprefix]
  616. if ans is None:
  617. ans = self.__namespaces.get(aprefix)
  618. if ans is not None:
  619. key = ans + ' ' + key
  620. else:
  621. key = aprefix + ':' + key
  622. nattrdict[key] = val
  623. attrnamemap[key] = okey
  624. attrdict = nattrdict
  625. attributes = self.attributes.get(nstag)
  626. if attributes is not None:
  627. for key in attrdict.keys():
  628. if not key in attributes:
  629. self.syntax_error("unknown attribute `%s' in tag `%s'" % (attrnamemap[key], tagname))
  630. for key, val in attributes.items():
  631. if val is not None and not key in attrdict:
  632. attrdict[key] = val
  633. method = self.elements.get(nstag, (None, None))[0]
  634. self.finish_starttag(nstag, attrdict, method)
  635. if tag.group('slash') == '/':
  636. self.finish_endtag(tagname)
  637. return tag.end(0)
  638. # Internal -- parse endtag
  639. def parse_endtag(self, i):
  640. rawdata = self.rawdata
  641. end = endbracketfind.match(rawdata, i+1)
  642. if end is None:
  643. return -1
  644. res = tagfind.match(rawdata, i+2)
  645. if res is None:
  646. if self.literal:
  647. self.handle_data(rawdata[i])
  648. return i+1
  649. if not self.__accept_missing_endtag_name:
  650. self.syntax_error('no name specified in end tag')
  651. tag = self.stack[-1][0]
  652. k = i+2
  653. else:
  654. tag = res.group(0)
  655. if self.__map_case:
  656. tag = tag.lower()
  657. if self.literal:
  658. if not self.stack or tag != self.stack[-1][0]:
  659. self.handle_data(rawdata[i])
  660. return i+1
  661. k = res.end(0)
  662. if endbracket.match(rawdata, k) is None:
  663. self.syntax_error('garbage in end tag')
  664. self.finish_endtag(tag)
  665. return end.end(0)
  666. # Internal -- finish processing of start tag
  667. def finish_starttag(self, tagname, attrdict, method):
  668. if method is not None:
  669. self.handle_starttag(tagname, method, attrdict)
  670. else:
  671. self.unknown_starttag(tagname, attrdict)
  672. # Internal -- finish processing of end tag
  673. def finish_endtag(self, tag):
  674. self.literal = 0
  675. if not tag:
  676. self.syntax_error('name-less end tag')
  677. found = len(self.stack) - 1
  678. if found < 0:
  679. self.unknown_endtag(tag)
  680. return
  681. else:
  682. found = -1
  683. for i in range(len(self.stack)):
  684. if tag == self.stack[i][0]:
  685. found = i
  686. if found == -1:
  687. self.syntax_error('unopened end tag')
  688. return
  689. while len(self.stack) > found:
  690. if found < len(self.stack) - 1:
  691. self.syntax_error('missing close tag for %s' % self.stack[-1][2])
  692. nstag = self.stack[-1][2]
  693. method = self.elements.get(nstag, (None, None))[1]
  694. if method is not None:
  695. self.handle_endtag(nstag, method)
  696. else:
  697. self.unknown_endtag(nstag)
  698. if self.__use_namespaces == len(self.stack):
  699. self.__use_namespaces = 0
  700. del self.stack[-1]
  701. # Overridable -- handle xml processing instruction
  702. def handle_xml(self, encoding, standalone):
  703. pass
  704. # Overridable -- handle DOCTYPE
  705. def handle_doctype(self, tag, pubid, syslit, data):
  706. pass
  707. # Overridable -- handle start tag
  708. def handle_starttag(self, tag, method, attrs):
  709. method(attrs)
  710. # Overridable -- handle end tag
  711. def handle_endtag(self, tag, method):
  712. method()
  713. # Example -- handle character reference, no need to override
  714. def handle_charref(self, name):
  715. try:
  716. if name[0] == 'x':
  717. n = int(name[1:], 16)
  718. else:
  719. n = int(name)
  720. except ValueError:
  721. self.unknown_charref(name)
  722. return
  723. if not 0 <= n <= 255:
  724. self.unknown_charref(name)
  725. return
  726. self.handle_data(chr(n))
  727. # Definition of entities -- derived classes may override
  728. entitydefs = {'lt': '&#60;', # must use charref
  729. 'gt': '&#62;',
  730. 'amp': '&#38;', # must use charref
  731. 'quot': '&#34;',
  732. 'apos': '&#39;',
  733. }
  734. # Example -- handle data, should be overridden
  735. def handle_data(self, data):
  736. pass
  737. # Example -- handle cdata, could be overridden
  738. def handle_cdata(self, data):
  739. pass
  740. # Example -- handle comment, could be overridden
  741. def handle_comment(self, data):
  742. pass
  743. # Example -- handle processing instructions, could be overridden
  744. def handle_proc(self, name, data):
  745. pass
  746. # Example -- handle relatively harmless syntax errors, could be overridden
  747. def syntax_error(self, message):
  748. raise Error('Syntax error at line %d: %s' % (self.lineno, message))
  749. # To be overridden -- handlers for unknown objects
  750. def unknown_starttag(self, tag, attrs): pass
  751. def unknown_endtag(self, tag): pass
  752. def unknown_charref(self, ref): pass
  753. def unknown_entityref(self, name):
  754. self.syntax_error("reference to unknown entity `&%s;'" % name)
  755. class TestXMLParser(XMLParser):
  756. def __init__(self, **kw):
  757. self.testdata = ""
  758. XMLParser.__init__(self, **kw)
  759. def handle_xml(self, encoding, standalone):
  760. self.flush()
  761. print 'xml: encoding =',encoding,'standalone =',standalone
  762. def handle_doctype(self, tag, pubid, syslit, data):
  763. self.flush()
  764. print 'DOCTYPE:',tag, repr(data)
  765. def handle_data(self, data):
  766. self.testdata = self.testdata + data
  767. if len(repr(self.testdata)) >= 70:
  768. self.flush()
  769. def flush(self):
  770. data = self.testdata
  771. if data:
  772. self.testdata = ""
  773. print 'data:', repr(data)
  774. def handle_cdata(self, data):
  775. self.flush()
  776. print 'cdata:', repr(data)
  777. def handle_proc(self, name, data):
  778. self.flush()
  779. print 'processing:',name,repr(data)
  780. def handle_comment(self, data):
  781. self.flush()
  782. r = repr(data)
  783. if len(r) > 68:
  784. r = r[:32] + '...' + r[-32:]
  785. print 'comment:', r
  786. def syntax_error(self, message):
  787. print 'error at line %d:' % self.lineno, message
  788. def unknown_starttag(self, tag, attrs):
  789. self.flush()
  790. if not attrs:
  791. print 'start tag: <' + tag + '>'
  792. else:
  793. print 'start tag: <' + tag,
  794. for name, value in attrs.items():
  795. print name + '=' + '"' + value + '"',
  796. print '>'
  797. def unknown_endtag(self, tag):
  798. self.flush()
  799. print 'end tag: </' + tag + '>'
  800. def unknown_entityref(self, ref):
  801. self.flush()
  802. print '*** unknown entity ref: &' + ref + ';'
  803. def unknown_charref(self, ref):
  804. self.flush()
  805. print '*** unknown char ref: &#' + ref + ';'
  806. def close(self):
  807. XMLParser.close(self)
  808. self.flush()
  809. def test(args = None):
  810. import sys, getopt
  811. from time import time
  812. if not args:
  813. args = sys.argv[1:]
  814. opts, args = getopt.getopt(args, 'st')
  815. klass = TestXMLParser
  816. do_time = 0
  817. for o, a in opts:
  818. if o == '-s':
  819. klass = XMLParser
  820. elif o == '-t':
  821. do_time = 1
  822. if args:
  823. file = args[0]
  824. else:
  825. file = 'test.xml'
  826. if file == '-':
  827. f = sys.stdin
  828. else:
  829. try:
  830. f = open(file, 'r')
  831. except IOError, msg:
  832. print file, ":", msg
  833. sys.exit(1)
  834. data = f.read()
  835. if f is not sys.stdin:
  836. f.close()
  837. x = klass()
  838. t0 = time()
  839. try:
  840. if do_time:
  841. x.feed(data)
  842. x.close()
  843. else:
  844. for c in data:
  845. x.feed(c)
  846. x.close()
  847. except Error, msg:
  848. t1 = time()
  849. print msg
  850. if do_time:
  851. print 'total time: %g' % (t1-t0)
  852. sys.exit(1)
  853. t1 = time()
  854. if do_time:
  855. print 'total time: %g' % (t1-t0)
  856. if __name__ == '__main__':
  857. test()