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