blob: e8210e6177f00d7953c905d3db7b2831b9d87eb0 [file] [log] [blame]
Guido van Rossum4b8c6ea2000-02-04 15:39:30 +00001"""A parser for XML, using the derived class as static DTD."""
2
Guido van Rossum5d68e8e1997-11-18 15:27:20 +00003# Author: Sjoerd Mullender.
Guido van Rossuma219efa1997-11-18 15:09:54 +00004
5import re
6import string
7
8
Guido van Rossumb35d6841999-08-26 15:52:33 +00009version = '0.3'
Guido van Rossum7e07b381998-04-03 16:02:39 +000010
Sjoerd Mullenderf7e84e12000-12-06 10:37:57 +000011class Error(RuntimeError):
12 pass
13
Guido van Rossuma219efa1997-11-18 15:09:54 +000014# Regular expressions used for parsing
15
Guido van Rossumeeb2f321998-10-19 13:28:26 +000016_S = '[ \t\r\n]+' # white space
17_opS = '[ \t\r\n]*' # optional white space
18_Name = '[a-zA-Z_:][-a-zA-Z0-9._:]*' # valid XML name
19_QStr = "(?:'[^']*'|\"[^\"]*\")" # quoted XML string
Guido van Rossum7e07b381998-04-03 16:02:39 +000020illegal = re.compile('[^\t\r\n -\176\240-\377]') # illegal chars in content
21interesting = re.compile('[]&<]')
Guido van Rossuma219efa1997-11-18 15:09:54 +000022
Guido van Rossum7e07b381998-04-03 16:02:39 +000023amp = re.compile('&')
24ref = re.compile('&(' + _Name + '|#[0-9]+|#x[0-9a-fA-F]+)[^-a-zA-Z0-9._:]')
Guido van Rossuma219efa1997-11-18 15:09:54 +000025entityref = re.compile('&(?P<name>' + _Name + ')[^-a-zA-Z0-9._:]')
26charref = re.compile('&#(?P<char>[0-9]+[^0-9]|x[0-9a-fA-F]+[^0-9a-fA-F])')
Guido van Rossum7e07b381998-04-03 16:02:39 +000027space = re.compile(_S + '$')
Guido van Rossuma219efa1997-11-18 15:09:54 +000028newline = re.compile('\n')
29
Guido van Rossumeeb2f321998-10-19 13:28:26 +000030attrfind = re.compile(
31 _S + '(?P<name>' + _Name + ')'
32 '(' + _opS + '=' + _opS +
Guido van Rossumd468bd32000-06-21 20:01:10 +000033 '(?P<value>'+_QStr+'|[-a-zA-Z0-9.:+*%?!\(\)_#=~]+))?')
Guido van Rossuma219efa1997-11-18 15:09:54 +000034starttagopen = re.compile('<' + _Name)
Guido van Rossuma219efa1997-11-18 15:09:54 +000035starttagend = re.compile(_opS + '(?P<slash>/?)>')
Guido van Rossumeeb2f321998-10-19 13:28:26 +000036starttagmatch = re.compile('<(?P<tagname>'+_Name+')'
37 '(?P<attrs>(?:'+attrfind.pattern+')*)'+
38 starttagend.pattern)
39endtagopen = re.compile('</')
Guido van Rossum7e07b381998-04-03 16:02:39 +000040endbracket = re.compile(_opS + '>')
Guido van Rossumeeb2f321998-10-19 13:28:26 +000041endbracketfind = re.compile('(?:[^>\'"]|'+_QStr+')*>')
Guido van Rossuma219efa1997-11-18 15:09:54 +000042tagfind = re.compile(_Name)
Guido van Rossum02505e41998-01-29 14:55:24 +000043cdataopen = re.compile(r'<!\[CDATA\[')
44cdataclose = re.compile(r'\]\]>')
Guido van Rossum7e07b381998-04-03 16:02:39 +000045# this matches one of the following:
46# SYSTEM SystemLiteral
47# PUBLIC PubidLiteral SystemLiteral
Guido van Rossumeeb2f321998-10-19 13:28:26 +000048_SystemLiteral = '(?P<%s>'+_QStr+')'
Guido van Rossumd468bd32000-06-21 20:01:10 +000049_PublicLiteral = '(?P<%s>"[-\'\(\)+,./:=?;!*#@$_%% \n\ra-zA-Z0-9]*"|' \
50 "'[-\(\)+,./:=?;!*#@$_%% \n\ra-zA-Z0-9]*')"
Guido van Rossum7e07b381998-04-03 16:02:39 +000051_ExternalId = '(?:SYSTEM|' \
52 'PUBLIC'+_S+_PublicLiteral%'pubid'+ \
53 ')'+_S+_SystemLiteral%'syslit'
54doctype = re.compile('<!DOCTYPE'+_S+'(?P<name>'+_Name+')'
55 '(?:'+_S+_ExternalId+')?'+_opS)
56xmldecl = re.compile('<\?xml'+_S+
Guido van Rossumeeb2f321998-10-19 13:28:26 +000057 'version'+_opS+'='+_opS+'(?P<version>'+_QStr+')'+
Guido van Rossum7e07b381998-04-03 16:02:39 +000058 '(?:'+_S+'encoding'+_opS+'='+_opS+
59 "(?P<encoding>'[A-Za-z][-A-Za-z0-9._]*'|"
60 '"[A-Za-z][-A-Za-z0-9._]*"))?'
61 '(?:'+_S+'standalone'+_opS+'='+_opS+
62 '(?P<standalone>\'(?:yes|no)\'|"(?:yes|no)"))?'+
63 _opS+'\?>')
64procopen = re.compile(r'<\?(?P<proc>' + _Name + ')' + _opS)
Guido van Rossum02505e41998-01-29 14:55:24 +000065procclose = re.compile(_opS + r'\?>')
Guido van Rossuma219efa1997-11-18 15:09:54 +000066commentopen = re.compile('<!--')
67commentclose = re.compile('-->')
68doubledash = re.compile('--')
Guido van Rossum7e07b381998-04-03 16:02:39 +000069attrtrans = string.maketrans(' \r\n\t', ' ')
Guido van Rossuma219efa1997-11-18 15:09:54 +000070
Guido van Rossumb083a9f1998-12-18 20:17:13 +000071# definitions for XML namespaces
72_NCName = '[a-zA-Z_][-a-zA-Z0-9._]*' # XML Name, minus the ":"
73ncname = re.compile(_NCName + '$')
74qname = re.compile('(?:(?P<prefix>' + _NCName + '):)?' # optional prefix
75 '(?P<local>' + _NCName + ')$')
76
77xmlns = re.compile('xmlns(?::(?P<ncname>'+_NCName+'))?$')
Guido van Rossuma219efa1997-11-18 15:09:54 +000078
79# XML parser base class -- find tags and call handler functions.
80# Usage: p = XMLParser(); p.feed(data); ...; p.close().
Guido van Rossum5d68e8e1997-11-18 15:27:20 +000081# The dtd is defined by deriving a class which defines methods with
82# special names to handle tags: start_foo and end_foo to handle <foo>
83# and </foo>, respectively. The data between tags is passed to the
84# parser by calling self.handle_data() with some data as argument (the
Jeremy Hyltona05e2932000-06-28 14:48:01 +000085# data may be split up in arbitrary chunks).
Guido van Rossuma219efa1997-11-18 15:09:54 +000086
87class XMLParser:
Guido van Rossumb083a9f1998-12-18 20:17:13 +000088 attributes = {} # default, to be overridden
89 elements = {} # default, to be overridden
Guido van Rossuma219efa1997-11-18 15:09:54 +000090
Guido van Rossumb35d6841999-08-26 15:52:33 +000091 # parsing options, settable using keyword args in __init__
92 __accept_unquoted_attributes = 0
93 __accept_missing_endtag_name = 0
94 __map_case = 0
95 __accept_utf8 = 0
Sjoerd Mullender5baaf662000-07-04 14:53:12 +000096 __translate_attribute_references = 1
Guido van Rossumb35d6841999-08-26 15:52:33 +000097
Guido van Rossuma219efa1997-11-18 15:09:54 +000098 # Interface -- initialize and reset this instance
Guido van Rossumb35d6841999-08-26 15:52:33 +000099 def __init__(self, **kw):
Guido van Rossumcc2c2911999-02-02 17:54:38 +0000100 self.__fixed = 0
Guido van Rossumb35d6841999-08-26 15:52:33 +0000101 if kw.has_key('accept_unquoted_attributes'):
102 self.__accept_unquoted_attributes = kw['accept_unquoted_attributes']
103 if kw.has_key('accept_missing_endtag_name'):
104 self.__accept_missing_endtag_name = kw['accept_missing_endtag_name']
105 if kw.has_key('map_case'):
106 self.__map_case = kw['map_case']
107 if kw.has_key('accept_utf8'):
108 self.__accept_utf8 = kw['accept_utf8']
Sjoerd Mullender5baaf662000-07-04 14:53:12 +0000109 if kw.has_key('translate_attribute_references'):
110 self.__translate_attribute_references = kw['translate_attribute_references']
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000111 self.reset()
Guido van Rossumfe649351999-02-01 15:35:13 +0000112
113 def __fixelements(self):
Guido van Rossumcc2c2911999-02-02 17:54:38 +0000114 self.__fixed = 1
Guido van Rossumfe649351999-02-01 15:35:13 +0000115 self.elements = {}
116 self.__fixdict(self.__dict__)
117 self.__fixclass(self.__class__)
118
119 def __fixclass(self, kl):
120 self.__fixdict(kl.__dict__)
121 for k in kl.__bases__:
122 self.__fixclass(k)
123
124 def __fixdict(self, dict):
Guido van Rossum2e3f7be1999-02-02 22:15:24 +0000125 for key in dict.keys():
Guido van Rossumfe649351999-02-01 15:35:13 +0000126 if key[:6] == 'start_':
Guido van Rossum2e3f7be1999-02-02 22:15:24 +0000127 tag = key[6:]
128 start, end = self.elements.get(tag, (None, None))
Guido van Rossumfe649351999-02-01 15:35:13 +0000129 if start is None:
Guido van Rossum2e3f7be1999-02-02 22:15:24 +0000130 self.elements[tag] = getattr(self, key), end
Guido van Rossumfe649351999-02-01 15:35:13 +0000131 elif key[:4] == 'end_':
Guido van Rossum2e3f7be1999-02-02 22:15:24 +0000132 tag = key[4:]
133 start, end = self.elements.get(tag, (None, None))
Guido van Rossumfe649351999-02-01 15:35:13 +0000134 if end is None:
Guido van Rossum2e3f7be1999-02-02 22:15:24 +0000135 self.elements[tag] = start, getattr(self, key)
Guido van Rossuma219efa1997-11-18 15:09:54 +0000136
137 # Interface -- reset this instance. Loses all unprocessed data
138 def reset(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000139 self.rawdata = ''
140 self.stack = []
141 self.nomoretags = 0
142 self.literal = 0
143 self.lineno = 1
144 self.__at_start = 1
145 self.__seen_doctype = None
146 self.__seen_starttag = 0
Guido van Rossum91c8f591998-12-21 18:15:28 +0000147 self.__use_namespaces = 0
Guido van Rossumb083a9f1998-12-18 20:17:13 +0000148 self.__namespaces = {'xml':None} # xml is implicitly declared
Thomas Wouters7e474022000-07-16 12:04:32 +0000149 # backward compatibility hack: if elements not overridden,
Guido van Rossumcc2c2911999-02-02 17:54:38 +0000150 # fill it in ourselves
151 if self.elements is XMLParser.elements:
152 self.__fixelements()
Guido van Rossuma219efa1997-11-18 15:09:54 +0000153
154 # For derived classes only -- enter literal mode (CDATA) till EOF
155 def setnomoretags(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000156 self.nomoretags = self.literal = 1
Guido van Rossuma219efa1997-11-18 15:09:54 +0000157
158 # For derived classes only -- enter literal mode (CDATA)
159 def setliteral(self, *args):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000160 self.literal = 1
Guido van Rossuma219efa1997-11-18 15:09:54 +0000161
162 # Interface -- feed some data to the parser. Call this as
163 # often as you want, with as little or as much text as you
164 # want (may include '\n'). (This just saves the text, all the
165 # processing is done by goahead().)
166 def feed(self, data):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000167 self.rawdata = self.rawdata + data
168 self.goahead(0)
Guido van Rossuma219efa1997-11-18 15:09:54 +0000169
170 # Interface -- handle the remaining data
171 def close(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000172 self.goahead(1)
Guido van Rossumcc2c2911999-02-02 17:54:38 +0000173 if self.__fixed:
174 self.__fixed = 0
175 # remove self.elements so that we don't leak
176 del self.elements
Guido van Rossuma219efa1997-11-18 15:09:54 +0000177
178 # Interface -- translate references
Guido van Rossum7e07b381998-04-03 16:02:39 +0000179 def translate_references(self, data, all = 1):
Sjoerd Mullender5baaf662000-07-04 14:53:12 +0000180 if not self.__translate_attribute_references:
181 return data
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000182 i = 0
183 while 1:
Guido van Rossum7e07b381998-04-03 16:02:39 +0000184 res = amp.search(data, i)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000185 if res is None:
Guido van Rossum7e07b381998-04-03 16:02:39 +0000186 return data
Sjoerd Mullenderf9850642000-07-10 08:09:48 +0000187 s = res.start(0)
188 res = ref.match(data, s)
Guido van Rossum7e07b381998-04-03 16:02:39 +0000189 if res is None:
190 self.syntax_error("bogus `&'")
Sjoerd Mullenderf9850642000-07-10 08:09:48 +0000191 i = s+1
Guido van Rossum7e07b381998-04-03 16:02:39 +0000192 continue
193 i = res.end(0)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000194 str = res.group(1)
Sjoerd Mullenderf9850642000-07-10 08:09:48 +0000195 rescan = 0
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000196 if str[0] == '#':
197 if str[1] == 'x':
Eric S. Raymondbe9b5072001-02-09 10:48:30 +0000198 str = chr(int(str[2:], 16))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000199 else:
Eric S. Raymondbe9b5072001-02-09 10:48:30 +0000200 str = chr(int(str[1:]))
Sjoerd Mullenderf9850642000-07-10 08:09:48 +0000201 if data[i - 1] != ';':
202 self.syntax_error("`;' missing after char reference")
203 i = i-1
Guido van Rossum7e07b381998-04-03 16:02:39 +0000204 elif all:
205 if self.entitydefs.has_key(str):
Sjoerd Mullenderf9850642000-07-10 08:09:48 +0000206 str = self.entitydefs[str]
207 rescan = 1
208 elif data[i - 1] != ';':
209 self.syntax_error("bogus `&'")
210 i = s + 1 # just past the &
211 continue
Guido van Rossum7e07b381998-04-03 16:02:39 +0000212 else:
Guido van Rossumcc2c2911999-02-02 17:54:38 +0000213 self.syntax_error("reference to unknown entity `&%s;'" % str)
Sjoerd Mullenderf9850642000-07-10 08:09:48 +0000214 str = '&' + str + ';'
215 elif data[i - 1] != ';':
216 self.syntax_error("bogus `&'")
217 i = s + 1 # just past the &
218 continue
219
220 # when we get here, str contains the translated text and i points
221 # to the end of the string that is to be replaced
222 data = data[:s] + str + data[i:]
223 if rescan:
224 i = s
Guido van Rossum7e07b381998-04-03 16:02:39 +0000225 else:
Sjoerd Mullenderf9850642000-07-10 08:09:48 +0000226 i = s + len(str)
Guido van Rossuma219efa1997-11-18 15:09:54 +0000227
Sjoerd Mullender1c8feae2000-08-31 10:27:00 +0000228 # Interface - return a dictionary of all namespaces currently valid
229 def getnamespace(self):
230 nsdict = {}
231 for t, d, nst in self.stack:
232 nsdict.update(d)
233 return nsdict
234
Guido van Rossuma219efa1997-11-18 15:09:54 +0000235 # Internal -- handle data as far as reasonable. May leave state
236 # and data to be processed by a subsequent call. If 'end' is
237 # true, force handling all data as if followed by EOF marker.
238 def goahead(self, end):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000239 rawdata = self.rawdata
240 i = 0
241 n = len(rawdata)
242 while i < n:
243 if i > 0:
244 self.__at_start = 0
245 if self.nomoretags:
246 data = rawdata[i:n]
247 self.handle_data(data)
Eric S. Raymondbe9b5072001-02-09 10:48:30 +0000248 self.lineno = self.lineno + data.count('\n')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000249 i = n
250 break
251 res = interesting.search(rawdata, i)
252 if res:
Tim Peterse1190062001-01-15 03:34:38 +0000253 j = res.start(0)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000254 else:
Tim Peterse1190062001-01-15 03:34:38 +0000255 j = n
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000256 if i < j:
Guido van Rossum91c8f591998-12-21 18:15:28 +0000257 data = rawdata[i:j]
258 if self.__at_start and space.match(data) is None:
Guido van Rossum7e07b381998-04-03 16:02:39 +0000259 self.syntax_error('illegal data at start of file')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000260 self.__at_start = 0
Guido van Rossumeeb2f321998-10-19 13:28:26 +0000261 if not self.stack and space.match(data) is None:
Guido van Rossum7e07b381998-04-03 16:02:39 +0000262 self.syntax_error('data not in content')
Guido van Rossumb35d6841999-08-26 15:52:33 +0000263 if not self.__accept_utf8 and illegal.search(data):
Guido van Rossum7e07b381998-04-03 16:02:39 +0000264 self.syntax_error('illegal character in content')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000265 self.handle_data(data)
Eric S. Raymondbe9b5072001-02-09 10:48:30 +0000266 self.lineno = self.lineno + data.count('\n')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000267 i = j
268 if i == n: break
269 if rawdata[i] == '<':
270 if starttagopen.match(rawdata, i):
271 if self.literal:
272 data = rawdata[i]
273 self.handle_data(data)
Eric S. Raymondbe9b5072001-02-09 10:48:30 +0000274 self.lineno = self.lineno + data.count('\n')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000275 i = i+1
276 continue
277 k = self.parse_starttag(i)
278 if k < 0: break
279 self.__seen_starttag = 1
Eric S. Raymondbe9b5072001-02-09 10:48:30 +0000280 self.lineno = self.lineno + rawdata[i:k].count('\n')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000281 i = k
282 continue
283 if endtagopen.match(rawdata, i):
284 k = self.parse_endtag(i)
285 if k < 0: break
Eric S. Raymondbe9b5072001-02-09 10:48:30 +0000286 self.lineno = self.lineno + rawdata[i:k].count('\n')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000287 i = k
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000288 continue
289 if commentopen.match(rawdata, i):
290 if self.literal:
291 data = rawdata[i]
292 self.handle_data(data)
Eric S. Raymondbe9b5072001-02-09 10:48:30 +0000293 self.lineno = self.lineno + data.count('\n')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000294 i = i+1
295 continue
296 k = self.parse_comment(i)
297 if k < 0: break
Eric S. Raymondbe9b5072001-02-09 10:48:30 +0000298 self.lineno = self.lineno + rawdata[i:k].count('\n')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000299 i = k
300 continue
301 if cdataopen.match(rawdata, i):
302 k = self.parse_cdata(i)
303 if k < 0: break
Eric S. Raymondbe9b5072001-02-09 10:48:30 +0000304 self.lineno = self.lineno + rawdata[i:k].count('\n')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000305 i = k
306 continue
Guido van Rossum7e07b381998-04-03 16:02:39 +0000307 res = xmldecl.match(rawdata, i)
308 if res:
309 if not self.__at_start:
310 self.syntax_error("<?xml?> declaration not at start of document")
311 version, encoding, standalone = res.group('version',
312 'encoding',
313 'standalone')
314 if version[1:-1] != '1.0':
Sjoerd Mullenderf7e84e12000-12-06 10:37:57 +0000315 raise Error('only XML version 1.0 supported')
Guido van Rossum7e07b381998-04-03 16:02:39 +0000316 if encoding: encoding = encoding[1:-1]
317 if standalone: standalone = standalone[1:-1]
318 self.handle_xml(encoding, standalone)
319 i = res.end(0)
320 continue
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000321 res = procopen.match(rawdata, i)
322 if res:
323 k = self.parse_proc(i)
324 if k < 0: break
Eric S. Raymondbe9b5072001-02-09 10:48:30 +0000325 self.lineno = self.lineno + rawdata[i:k].count('\n')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000326 i = k
327 continue
328 res = doctype.match(rawdata, i)
329 if res:
330 if self.literal:
331 data = rawdata[i]
332 self.handle_data(data)
Eric S. Raymondbe9b5072001-02-09 10:48:30 +0000333 self.lineno = self.lineno + data.count('\n')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000334 i = i+1
335 continue
336 if self.__seen_doctype:
337 self.syntax_error('multiple DOCTYPE elements')
338 if self.__seen_starttag:
339 self.syntax_error('DOCTYPE not at beginning of document')
340 k = self.parse_doctype(res)
341 if k < 0: break
342 self.__seen_doctype = res.group('name')
Guido van Rossumb35d6841999-08-26 15:52:33 +0000343 if self.__map_case:
Eric S. Raymondbe9b5072001-02-09 10:48:30 +0000344 self.__seen_doctype = self.__seen_doctype.lower()
345 self.lineno = self.lineno + rawdata[i:k].count('\n')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000346 i = k
347 continue
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000348 elif rawdata[i] == '&':
Guido van Rossum204b65c1998-12-08 13:25:00 +0000349 if self.literal:
350 data = rawdata[i]
351 self.handle_data(data)
352 i = i+1
353 continue
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000354 res = charref.match(rawdata, i)
355 if res is not None:
356 i = res.end(0)
357 if rawdata[i-1] != ';':
358 self.syntax_error("`;' missing in charref")
359 i = i-1
Guido van Rossum7e07b381998-04-03 16:02:39 +0000360 if not self.stack:
361 self.syntax_error('data not in content')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000362 self.handle_charref(res.group('char')[:-1])
Eric S. Raymondbe9b5072001-02-09 10:48:30 +0000363 self.lineno = self.lineno + res.group(0).count('\n')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000364 continue
365 res = entityref.match(rawdata, i)
366 if res is not None:
367 i = res.end(0)
368 if rawdata[i-1] != ';':
369 self.syntax_error("`;' missing in entityref")
370 i = i-1
Guido van Rossum7e07b381998-04-03 16:02:39 +0000371 name = res.group('name')
Guido van Rossumb35d6841999-08-26 15:52:33 +0000372 if self.__map_case:
Eric S. Raymondbe9b5072001-02-09 10:48:30 +0000373 name = name.lower()
Guido van Rossum7e07b381998-04-03 16:02:39 +0000374 if self.entitydefs.has_key(name):
375 self.rawdata = rawdata = rawdata[:res.start(0)] + self.entitydefs[name] + rawdata[i:]
376 n = len(rawdata)
377 i = res.start(0)
378 else:
Guido van Rossum7e07b381998-04-03 16:02:39 +0000379 self.unknown_entityref(name)
Eric S. Raymondbe9b5072001-02-09 10:48:30 +0000380 self.lineno = self.lineno + res.group(0).count('\n')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000381 continue
Guido van Rossum7e07b381998-04-03 16:02:39 +0000382 elif rawdata[i] == ']':
Guido van Rossum204b65c1998-12-08 13:25:00 +0000383 if self.literal:
384 data = rawdata[i]
385 self.handle_data(data)
386 i = i+1
387 continue
Guido van Rossum7e07b381998-04-03 16:02:39 +0000388 if n-i < 3:
389 break
390 if cdataclose.match(rawdata, i):
391 self.syntax_error("bogus `]]>'")
392 self.handle_data(rawdata[i])
393 i = i+1
394 continue
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000395 else:
Sjoerd Mullenderf7e84e12000-12-06 10:37:57 +0000396 raise Error('neither < nor & ??')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000397 # We get here only if incomplete matches but
398 # nothing else
Guido van Rossum7e07b381998-04-03 16:02:39 +0000399 break
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000400 # end while
Guido van Rossum7e07b381998-04-03 16:02:39 +0000401 if i > 0:
402 self.__at_start = 0
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000403 if end and i < n:
Guido van Rossum7e07b381998-04-03 16:02:39 +0000404 data = rawdata[i]
405 self.syntax_error("bogus `%s'" % data)
Guido van Rossumb35d6841999-08-26 15:52:33 +0000406 if not self.__accept_utf8 and illegal.search(data):
Guido van Rossum7e07b381998-04-03 16:02:39 +0000407 self.syntax_error('illegal character in content')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000408 self.handle_data(data)
Eric S. Raymondbe9b5072001-02-09 10:48:30 +0000409 self.lineno = self.lineno + data.count('\n')
Guido van Rossum7e07b381998-04-03 16:02:39 +0000410 self.rawdata = rawdata[i+1:]
411 return self.goahead(end)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000412 self.rawdata = rawdata[i:]
413 if end:
Guido van Rossum7e07b381998-04-03 16:02:39 +0000414 if not self.__seen_starttag:
415 self.syntax_error('no elements in file')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000416 if self.stack:
417 self.syntax_error('missing end tags')
418 while self.stack:
Guido van Rossumb083a9f1998-12-18 20:17:13 +0000419 self.finish_endtag(self.stack[-1][0])
Guido van Rossuma219efa1997-11-18 15:09:54 +0000420
421 # Internal -- parse comment, return length or -1 if not terminated
422 def parse_comment(self, i):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000423 rawdata = self.rawdata
Fred Drake8152d322000-12-12 23:20:45 +0000424 if rawdata[i:i+4] != '<!--':
Sjoerd Mullenderf7e84e12000-12-06 10:37:57 +0000425 raise Error('unexpected call to handle_comment')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000426 res = commentclose.search(rawdata, i+4)
Guido van Rossumeeb2f321998-10-19 13:28:26 +0000427 if res is None:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000428 return -1
Guido van Rossum7e07b381998-04-03 16:02:39 +0000429 if doubledash.search(rawdata, i+4, res.start(0)):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000430 self.syntax_error("`--' inside comment")
Guido van Rossum7e07b381998-04-03 16:02:39 +0000431 if rawdata[res.start(0)-1] == '-':
432 self.syntax_error('comment cannot end in three dashes')
Guido van Rossumb35d6841999-08-26 15:52:33 +0000433 if not self.__accept_utf8 and \
434 illegal.search(rawdata, i+4, res.start(0)):
Guido van Rossum7e07b381998-04-03 16:02:39 +0000435 self.syntax_error('illegal character in comment')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000436 self.handle_comment(rawdata[i+4: res.start(0)])
437 return res.end(0)
Guido van Rossuma219efa1997-11-18 15:09:54 +0000438
Guido van Rossum02505e41998-01-29 14:55:24 +0000439 # Internal -- handle DOCTYPE tag, return length or -1 if not terminated
440 def parse_doctype(self, res):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000441 rawdata = self.rawdata
442 n = len(rawdata)
443 name = res.group('name')
Guido van Rossumb35d6841999-08-26 15:52:33 +0000444 if self.__map_case:
Eric S. Raymondbe9b5072001-02-09 10:48:30 +0000445 name = name.lower()
Guido van Rossum7e07b381998-04-03 16:02:39 +0000446 pubid, syslit = res.group('pubid', 'syslit')
447 if pubid is not None:
448 pubid = pubid[1:-1] # remove quotes
Eric S. Raymondbe9b5072001-02-09 10:48:30 +0000449 pubid = ' '.join(pubid.split()) # normalize
Guido van Rossum7e07b381998-04-03 16:02:39 +0000450 if syslit is not None: syslit = syslit[1:-1] # remove quotes
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000451 j = k = res.end(0)
Guido van Rossum7e07b381998-04-03 16:02:39 +0000452 if k >= n:
453 return -1
454 if rawdata[k] == '[':
455 level = 0
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000456 k = k+1
Guido van Rossum7e07b381998-04-03 16:02:39 +0000457 dq = sq = 0
458 while k < n:
459 c = rawdata[k]
460 if not sq and c == '"':
461 dq = not dq
462 elif not dq and c == "'":
463 sq = not sq
464 elif sq or dq:
465 pass
466 elif level <= 0 and c == ']':
467 res = endbracket.match(rawdata, k+1)
Guido van Rossumeeb2f321998-10-19 13:28:26 +0000468 if res is None:
Guido van Rossum7e07b381998-04-03 16:02:39 +0000469 return -1
470 self.handle_doctype(name, pubid, syslit, rawdata[j+1:k])
471 return res.end(0)
472 elif c == '<':
473 level = level + 1
474 elif c == '>':
475 level = level - 1
476 if level < 0:
477 self.syntax_error("bogus `>' in DOCTYPE")
478 k = k+1
Guido van Rossumeeb2f321998-10-19 13:28:26 +0000479 res = endbracketfind.match(rawdata, k)
480 if res is None:
Guido van Rossum7e07b381998-04-03 16:02:39 +0000481 return -1
Guido van Rossumeeb2f321998-10-19 13:28:26 +0000482 if endbracket.match(rawdata, k) is None:
Guido van Rossum7e07b381998-04-03 16:02:39 +0000483 self.syntax_error('garbage in DOCTYPE')
484 self.handle_doctype(name, pubid, syslit, None)
485 return res.end(0)
Guido van Rossum02505e41998-01-29 14:55:24 +0000486
487 # Internal -- handle CDATA tag, return length or -1 if not terminated
Guido van Rossuma219efa1997-11-18 15:09:54 +0000488 def parse_cdata(self, i):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000489 rawdata = self.rawdata
Fred Drake8152d322000-12-12 23:20:45 +0000490 if rawdata[i:i+9] != '<![CDATA[':
Sjoerd Mullenderf7e84e12000-12-06 10:37:57 +0000491 raise Error('unexpected call to parse_cdata')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000492 res = cdataclose.search(rawdata, i+9)
Guido van Rossumeeb2f321998-10-19 13:28:26 +0000493 if res is None:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000494 return -1
Guido van Rossumb35d6841999-08-26 15:52:33 +0000495 if not self.__accept_utf8 and \
496 illegal.search(rawdata, i+9, res.start(0)):
Guido van Rossum7e07b381998-04-03 16:02:39 +0000497 self.syntax_error('illegal character in CDATA')
498 if not self.stack:
499 self.syntax_error('CDATA not in content')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000500 self.handle_cdata(rawdata[i+9:res.start(0)])
501 return res.end(0)
Guido van Rossuma219efa1997-11-18 15:09:54 +0000502
Guido van Rossumb083a9f1998-12-18 20:17:13 +0000503 __xml_namespace_attributes = {'ns':None, 'src':None, 'prefix':None}
Guido van Rossum02505e41998-01-29 14:55:24 +0000504 # Internal -- handle a processing instruction tag
505 def parse_proc(self, i):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000506 rawdata = self.rawdata
507 end = procclose.search(rawdata, i)
Guido van Rossumeeb2f321998-10-19 13:28:26 +0000508 if end is None:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000509 return -1
510 j = end.start(0)
Guido van Rossumb35d6841999-08-26 15:52:33 +0000511 if not self.__accept_utf8 and illegal.search(rawdata, i+2, j):
Guido van Rossum7e07b381998-04-03 16:02:39 +0000512 self.syntax_error('illegal character in processing instruction')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000513 res = tagfind.match(rawdata, i+2)
Guido van Rossumeeb2f321998-10-19 13:28:26 +0000514 if res is None:
Sjoerd Mullenderf7e84e12000-12-06 10:37:57 +0000515 raise Error('unexpected call to parse_proc')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000516 k = res.end(0)
517 name = res.group(0)
Guido van Rossumb35d6841999-08-26 15:52:33 +0000518 if self.__map_case:
Eric S. Raymondbe9b5072001-02-09 10:48:30 +0000519 name = name.lower()
Guido van Rossumb083a9f1998-12-18 20:17:13 +0000520 if name == 'xml:namespace':
521 self.syntax_error('old-fashioned namespace declaration')
Guido van Rossum91c8f591998-12-21 18:15:28 +0000522 self.__use_namespaces = -1
Guido van Rossumb083a9f1998-12-18 20:17:13 +0000523 # namespace declaration
524 # this must come after the <?xml?> declaration (if any)
525 # and before the <!DOCTYPE> (if any).
526 if self.__seen_doctype or self.__seen_starttag:
527 self.syntax_error('xml:namespace declaration too late in document')
528 attrdict, namespace, k = self.parse_attributes(name, k, j)
529 if namespace:
530 self.syntax_error('namespace declaration inside namespace declaration')
531 for attrname in attrdict.keys():
532 if not self.__xml_namespace_attributes.has_key(attrname):
533 self.syntax_error("unknown attribute `%s' in xml:namespace tag" % attrname)
534 if not attrdict.has_key('ns') or not attrdict.has_key('prefix'):
535 self.syntax_error('xml:namespace without required attributes')
536 prefix = attrdict.get('prefix')
537 if ncname.match(prefix) is None:
538 self.syntax_error('xml:namespace illegal prefix value')
539 return end.end(0)
540 if self.__namespaces.has_key(prefix):
541 self.syntax_error('xml:namespace prefix not unique')
542 self.__namespaces[prefix] = attrdict['ns']
543 else:
Eric S. Raymondbe9b5072001-02-09 10:48:30 +0000544 if name.lower() == 'xml':
Guido van Rossumb083a9f1998-12-18 20:17:13 +0000545 self.syntax_error('illegal processing instruction target name')
546 self.handle_proc(name, rawdata[k:j])
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000547 return end.end(0)
Guido van Rossum02505e41998-01-29 14:55:24 +0000548
549 # Internal -- parse attributes between i and j
Guido van Rossumb083a9f1998-12-18 20:17:13 +0000550 def parse_attributes(self, tag, i, j):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000551 rawdata = self.rawdata
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000552 attrdict = {}
Guido van Rossumb083a9f1998-12-18 20:17:13 +0000553 namespace = {}
Guido van Rossumeeb2f321998-10-19 13:28:26 +0000554 while i < j:
555 res = attrfind.match(rawdata, i)
556 if res is None:
557 break
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000558 attrname, attrvalue = res.group('name', 'value')
Guido van Rossumb35d6841999-08-26 15:52:33 +0000559 if self.__map_case:
Eric S. Raymondbe9b5072001-02-09 10:48:30 +0000560 attrname = attrname.lower()
Guido van Rossumb083a9f1998-12-18 20:17:13 +0000561 i = res.end(0)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000562 if attrvalue is None:
Guido van Rossumeeb2f321998-10-19 13:28:26 +0000563 self.syntax_error("no value specified for attribute `%s'" % attrname)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000564 attrvalue = attrname
565 elif attrvalue[:1] == "'" == attrvalue[-1:] or \
566 attrvalue[:1] == '"' == attrvalue[-1:]:
567 attrvalue = attrvalue[1:-1]
Guido van Rossumb35d6841999-08-26 15:52:33 +0000568 elif not self.__accept_unquoted_attributes:
Guido van Rossumeeb2f321998-10-19 13:28:26 +0000569 self.syntax_error("attribute `%s' value not quoted" % attrname)
Guido van Rossumb083a9f1998-12-18 20:17:13 +0000570 res = xmlns.match(attrname)
571 if res is not None:
572 # namespace declaration
573 ncname = res.group('ncname')
574 namespace[ncname or ''] = attrvalue or None
Guido van Rossum91c8f591998-12-21 18:15:28 +0000575 if not self.__use_namespaces:
576 self.__use_namespaces = len(self.stack)+1
Guido van Rossumb083a9f1998-12-18 20:17:13 +0000577 continue
Guido van Rossumeeb2f321998-10-19 13:28:26 +0000578 if '<' in attrvalue:
579 self.syntax_error("`<' illegal in attribute value")
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000580 if attrdict.has_key(attrname):
Guido van Rossumeeb2f321998-10-19 13:28:26 +0000581 self.syntax_error("attribute `%s' specified twice" % attrname)
Eric S. Raymondbe9b5072001-02-09 10:48:30 +0000582 attrvalue = attrvalue.translate(attrtrans)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000583 attrdict[attrname] = self.translate_references(attrvalue)
Guido van Rossumb083a9f1998-12-18 20:17:13 +0000584 return attrdict, namespace, i
Guido van Rossuma219efa1997-11-18 15:09:54 +0000585
586 # Internal -- handle starttag, return length or -1 if not terminated
587 def parse_starttag(self, i):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000588 rawdata = self.rawdata
589 # i points to start of tag
Guido van Rossumeeb2f321998-10-19 13:28:26 +0000590 end = endbracketfind.match(rawdata, i+1)
591 if end is None:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000592 return -1
Guido van Rossumeeb2f321998-10-19 13:28:26 +0000593 tag = starttagmatch.match(rawdata, i)
594 if tag is None or tag.end(0) != end.end(0):
595 self.syntax_error('garbage in starttag')
596 return end.end(0)
Guido van Rossumb083a9f1998-12-18 20:17:13 +0000597 nstag = tagname = tag.group('tagname')
Guido van Rossumb35d6841999-08-26 15:52:33 +0000598 if self.__map_case:
Eric S. Raymondbe9b5072001-02-09 10:48:30 +0000599 nstag = tagname = nstag.lower()
Guido van Rossumeeb2f321998-10-19 13:28:26 +0000600 if not self.__seen_starttag and self.__seen_doctype and \
601 tagname != self.__seen_doctype:
602 self.syntax_error('starttag does not match DOCTYPE')
Guido van Rossum7e07b381998-04-03 16:02:39 +0000603 if self.__seen_starttag and not self.stack:
604 self.syntax_error('multiple elements on top level')
Guido van Rossumeeb2f321998-10-19 13:28:26 +0000605 k, j = tag.span('attrs')
Guido van Rossumb083a9f1998-12-18 20:17:13 +0000606 attrdict, nsdict, k = self.parse_attributes(tagname, k, j)
607 self.stack.append((tagname, nsdict, nstag))
Guido van Rossum91c8f591998-12-21 18:15:28 +0000608 if self.__use_namespaces:
609 res = qname.match(tagname)
610 else:
611 res = None
Guido van Rossumb083a9f1998-12-18 20:17:13 +0000612 if res is not None:
613 prefix, nstag = res.group('prefix', 'local')
614 if prefix is None:
615 prefix = ''
616 ns = None
617 for t, d, nst in self.stack:
618 if d.has_key(prefix):
619 ns = d[prefix]
620 if ns is None and prefix != '':
621 ns = self.__namespaces.get(prefix)
622 if ns is not None:
623 nstag = ns + ' ' + nstag
624 elif prefix != '':
625 nstag = prefix + ':' + nstag # undo split
626 self.stack[-1] = tagname, nsdict, nstag
627 # translate namespace of attributes
Sjoerd Mullenderf7e84e12000-12-06 10:37:57 +0000628 attrnamemap = {} # map from new name to old name (used for error reporting)
629 for key in attrdict.keys():
630 attrnamemap[key] = key
Guido van Rossum91c8f591998-12-21 18:15:28 +0000631 if self.__use_namespaces:
632 nattrdict = {}
633 for key, val in attrdict.items():
Sjoerd Mullenderf7e84e12000-12-06 10:37:57 +0000634 okey = key
Guido van Rossum91c8f591998-12-21 18:15:28 +0000635 res = qname.match(key)
636 if res is not None:
637 aprefix, key = res.group('prefix', 'local')
Guido van Rossumb35d6841999-08-26 15:52:33 +0000638 if self.__map_case:
Eric S. Raymondbe9b5072001-02-09 10:48:30 +0000639 key = key.lower()
Guido van Rossum91c8f591998-12-21 18:15:28 +0000640 if aprefix is None:
641 aprefix = ''
642 ans = None
643 for t, d, nst in self.stack:
644 if d.has_key(aprefix):
645 ans = d[aprefix]
646 if ans is None and aprefix != '':
647 ans = self.__namespaces.get(aprefix)
648 if ans is not None:
649 key = ans + ' ' + key
650 elif aprefix != '':
651 key = aprefix + ':' + key
652 elif ns is not None:
653 key = ns + ' ' + key
654 nattrdict[key] = val
Sjoerd Mullenderf7e84e12000-12-06 10:37:57 +0000655 attrnamemap[key] = okey
Guido van Rossum91c8f591998-12-21 18:15:28 +0000656 attrdict = nattrdict
Guido van Rossumb083a9f1998-12-18 20:17:13 +0000657 attributes = self.attributes.get(nstag)
658 if attributes is not None:
659 for key in attrdict.keys():
660 if not attributes.has_key(key):
Sjoerd Mullenderf7e84e12000-12-06 10:37:57 +0000661 self.syntax_error("unknown attribute `%s' in tag `%s'" % (attrnamemap[key], tagname))
Guido van Rossumb083a9f1998-12-18 20:17:13 +0000662 for key, val in attributes.items():
663 if val is not None and not attrdict.has_key(key):
664 attrdict[key] = val
665 method = self.elements.get(nstag, (None, None))[0]
666 self.finish_starttag(nstag, attrdict, method)
Guido van Rossumeeb2f321998-10-19 13:28:26 +0000667 if tag.group('slash') == '/':
668 self.finish_endtag(tagname)
669 return tag.end(0)
Guido van Rossuma219efa1997-11-18 15:09:54 +0000670
671 # Internal -- parse endtag
672 def parse_endtag(self, i):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000673 rawdata = self.rawdata
Guido van Rossumeeb2f321998-10-19 13:28:26 +0000674 end = endbracketfind.match(rawdata, i+1)
675 if end is None:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000676 return -1
677 res = tagfind.match(rawdata, i+2)
Guido van Rossumeeb2f321998-10-19 13:28:26 +0000678 if res is None:
Guido van Rossumf484a331998-12-07 21:59:56 +0000679 if self.literal:
680 self.handle_data(rawdata[i])
681 return i+1
Guido van Rossumb35d6841999-08-26 15:52:33 +0000682 if not self.__accept_missing_endtag_name:
683 self.syntax_error('no name specified in end tag')
Guido van Rossumd468bd32000-06-21 20:01:10 +0000684 tag = self.stack[-1][0]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000685 k = i+2
686 else:
687 tag = res.group(0)
Guido van Rossumb35d6841999-08-26 15:52:33 +0000688 if self.__map_case:
Eric S. Raymondbe9b5072001-02-09 10:48:30 +0000689 tag = tag.lower()
Guido van Rossumf484a331998-12-07 21:59:56 +0000690 if self.literal:
Guido van Rossumb083a9f1998-12-18 20:17:13 +0000691 if not self.stack or tag != self.stack[-1][0]:
Guido van Rossumf484a331998-12-07 21:59:56 +0000692 self.handle_data(rawdata[i])
693 return i+1
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000694 k = res.end(0)
Guido van Rossumeeb2f321998-10-19 13:28:26 +0000695 if endbracket.match(rawdata, k) is None:
Guido van Rossum7e07b381998-04-03 16:02:39 +0000696 self.syntax_error('garbage in end tag')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000697 self.finish_endtag(tag)
698 return end.end(0)
Guido van Rossuma219efa1997-11-18 15:09:54 +0000699
700 # Internal -- finish processing of start tag
Guido van Rossumb083a9f1998-12-18 20:17:13 +0000701 def finish_starttag(self, tagname, attrdict, method):
702 if method is not None:
703 self.handle_starttag(tagname, method, attrdict)
Guido van Rossum7e07b381998-04-03 16:02:39 +0000704 else:
Guido van Rossumb083a9f1998-12-18 20:17:13 +0000705 self.unknown_starttag(tagname, attrdict)
Guido van Rossuma219efa1997-11-18 15:09:54 +0000706
707 # Internal -- finish processing of end tag
708 def finish_endtag(self, tag):
Sjoerd Mullender538453e2001-03-14 17:03:30 +0000709 self.literal = 0
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000710 if not tag:
711 self.syntax_error('name-less end tag')
712 found = len(self.stack) - 1
713 if found < 0:
714 self.unknown_endtag(tag)
715 return
716 else:
Guido van Rossumb083a9f1998-12-18 20:17:13 +0000717 found = -1
718 for i in range(len(self.stack)):
719 if tag == self.stack[i][0]:
720 found = i
721 if found == -1:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000722 self.syntax_error('unopened end tag')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000723 return
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000724 while len(self.stack) > found:
725 if found < len(self.stack) - 1:
Guido van Rossumb083a9f1998-12-18 20:17:13 +0000726 self.syntax_error('missing close tag for %s' % self.stack[-1][2])
727 nstag = self.stack[-1][2]
728 method = self.elements.get(nstag, (None, None))[1]
729 if method is not None:
730 self.handle_endtag(nstag, method)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000731 else:
Guido van Rossumb083a9f1998-12-18 20:17:13 +0000732 self.unknown_endtag(nstag)
Guido van Rossum91c8f591998-12-21 18:15:28 +0000733 if self.__use_namespaces == len(self.stack):
734 self.__use_namespaces = 0
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000735 del self.stack[-1]
Guido van Rossuma219efa1997-11-18 15:09:54 +0000736
Guido van Rossum02505e41998-01-29 14:55:24 +0000737 # Overridable -- handle xml processing instruction
738 def handle_xml(self, encoding, standalone):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000739 pass
Guido van Rossum02505e41998-01-29 14:55:24 +0000740
741 # Overridable -- handle DOCTYPE
Guido van Rossum7e07b381998-04-03 16:02:39 +0000742 def handle_doctype(self, tag, pubid, syslit, data):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000743 pass
Guido van Rossum02505e41998-01-29 14:55:24 +0000744
Guido van Rossuma219efa1997-11-18 15:09:54 +0000745 # Overridable -- handle start tag
746 def handle_starttag(self, tag, method, attrs):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000747 method(attrs)
Guido van Rossuma219efa1997-11-18 15:09:54 +0000748
749 # Overridable -- handle end tag
750 def handle_endtag(self, tag, method):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000751 method()
Guido van Rossuma219efa1997-11-18 15:09:54 +0000752
753 # Example -- handle character reference, no need to override
754 def handle_charref(self, name):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000755 try:
756 if name[0] == 'x':
Eric S. Raymondbe9b5072001-02-09 10:48:30 +0000757 n = int(name[1:], 16)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000758 else:
Eric S. Raymondbe9b5072001-02-09 10:48:30 +0000759 n = int(name)
760 except ValueError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000761 self.unknown_charref(name)
762 return
763 if not 0 <= n <= 255:
764 self.unknown_charref(name)
765 return
766 self.handle_data(chr(n))
Guido van Rossuma219efa1997-11-18 15:09:54 +0000767
768 # Definition of entities -- derived classes may override
Guido van Rossum7e07b381998-04-03 16:02:39 +0000769 entitydefs = {'lt': '&#60;', # must use charref
770 'gt': '&#62;',
771 'amp': '&#38;', # must use charref
772 'quot': '&#34;',
773 'apos': '&#39;',
774 }
Guido van Rossuma219efa1997-11-18 15:09:54 +0000775
Guido van Rossuma219efa1997-11-18 15:09:54 +0000776 # Example -- handle data, should be overridden
777 def handle_data(self, data):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000778 pass
Guido van Rossuma219efa1997-11-18 15:09:54 +0000779
780 # Example -- handle cdata, could be overridden
781 def handle_cdata(self, data):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000782 pass
Guido van Rossuma219efa1997-11-18 15:09:54 +0000783
784 # Example -- handle comment, could be overridden
785 def handle_comment(self, data):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000786 pass
Guido van Rossuma219efa1997-11-18 15:09:54 +0000787
788 # Example -- handle processing instructions, could be overridden
789 def handle_proc(self, name, data):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000790 pass
Guido van Rossuma219efa1997-11-18 15:09:54 +0000791
Guido van Rossuma219efa1997-11-18 15:09:54 +0000792 # Example -- handle relatively harmless syntax errors, could be overridden
Guido van Rossum02505e41998-01-29 14:55:24 +0000793 def syntax_error(self, message):
Sjoerd Mullenderf7e84e12000-12-06 10:37:57 +0000794 raise Error('Syntax error at line %d: %s' % (self.lineno, message))
Guido van Rossuma219efa1997-11-18 15:09:54 +0000795
796 # To be overridden -- handlers for unknown objects
797 def unknown_starttag(self, tag, attrs): pass
798 def unknown_endtag(self, tag): pass
799 def unknown_charref(self, ref): pass
Guido van Rossumb35d6841999-08-26 15:52:33 +0000800 def unknown_entityref(self, name):
801 self.syntax_error("reference to unknown entity `&%s;'" % name)
Guido van Rossuma219efa1997-11-18 15:09:54 +0000802
803
804class TestXMLParser(XMLParser):
805
Guido van Rossumb35d6841999-08-26 15:52:33 +0000806 def __init__(self, **kw):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000807 self.testdata = ""
Guido van Rossumb35d6841999-08-26 15:52:33 +0000808 apply(XMLParser.__init__, (self,), kw)
Guido van Rossuma219efa1997-11-18 15:09:54 +0000809
Guido van Rossum02505e41998-01-29 14:55:24 +0000810 def handle_xml(self, encoding, standalone):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000811 self.flush()
812 print 'xml: encoding =',encoding,'standalone =',standalone
Guido van Rossum02505e41998-01-29 14:55:24 +0000813
Guido van Rossum7e07b381998-04-03 16:02:39 +0000814 def handle_doctype(self, tag, pubid, syslit, data):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000815 self.flush()
816 print 'DOCTYPE:',tag, `data`
Guido van Rossum02505e41998-01-29 14:55:24 +0000817
Guido van Rossuma219efa1997-11-18 15:09:54 +0000818 def handle_data(self, data):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000819 self.testdata = self.testdata + data
820 if len(`self.testdata`) >= 70:
821 self.flush()
Guido van Rossuma219efa1997-11-18 15:09:54 +0000822
823 def flush(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000824 data = self.testdata
825 if data:
826 self.testdata = ""
827 print 'data:', `data`
Guido van Rossuma219efa1997-11-18 15:09:54 +0000828
829 def handle_cdata(self, data):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000830 self.flush()
831 print 'cdata:', `data`
Guido van Rossuma219efa1997-11-18 15:09:54 +0000832
833 def handle_proc(self, name, data):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000834 self.flush()
835 print 'processing:',name,`data`
Guido van Rossuma219efa1997-11-18 15:09:54 +0000836
Guido van Rossuma219efa1997-11-18 15:09:54 +0000837 def handle_comment(self, data):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000838 self.flush()
839 r = `data`
840 if len(r) > 68:
841 r = r[:32] + '...' + r[-32:]
842 print 'comment:', r
Guido van Rossuma219efa1997-11-18 15:09:54 +0000843
Guido van Rossum02505e41998-01-29 14:55:24 +0000844 def syntax_error(self, message):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000845 print 'error at line %d:' % self.lineno, message
Guido van Rossuma219efa1997-11-18 15:09:54 +0000846
847 def unknown_starttag(self, tag, attrs):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000848 self.flush()
849 if not attrs:
850 print 'start tag: <' + tag + '>'
851 else:
852 print 'start tag: <' + tag,
853 for name, value in attrs.items():
854 print name + '=' + '"' + value + '"',
855 print '>'
Guido van Rossuma219efa1997-11-18 15:09:54 +0000856
857 def unknown_endtag(self, tag):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000858 self.flush()
859 print 'end tag: </' + tag + '>'
Guido van Rossuma219efa1997-11-18 15:09:54 +0000860
861 def unknown_entityref(self, ref):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000862 self.flush()
863 print '*** unknown entity ref: &' + ref + ';'
Guido van Rossuma219efa1997-11-18 15:09:54 +0000864
865 def unknown_charref(self, ref):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000866 self.flush()
867 print '*** unknown char ref: &#' + ref + ';'
Guido van Rossuma219efa1997-11-18 15:09:54 +0000868
869 def close(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000870 XMLParser.close(self)
871 self.flush()
Guido van Rossuma219efa1997-11-18 15:09:54 +0000872
873def test(args = None):
Guido van Rossumaf5add41998-12-22 14:23:50 +0000874 import sys, getopt
875 from time import time
Guido van Rossuma219efa1997-11-18 15:09:54 +0000876
877 if not args:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000878 args = sys.argv[1:]
Guido van Rossuma219efa1997-11-18 15:09:54 +0000879
Guido van Rossumaf5add41998-12-22 14:23:50 +0000880 opts, args = getopt.getopt(args, 'st')
881 klass = TestXMLParser
882 do_time = 0
883 for o, a in opts:
884 if o == '-s':
885 klass = XMLParser
886 elif o == '-t':
887 do_time = 1
Guido van Rossuma219efa1997-11-18 15:09:54 +0000888
889 if args:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000890 file = args[0]
Guido van Rossuma219efa1997-11-18 15:09:54 +0000891 else:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000892 file = 'test.xml'
Guido van Rossuma219efa1997-11-18 15:09:54 +0000893
894 if file == '-':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000895 f = sys.stdin
Guido van Rossuma219efa1997-11-18 15:09:54 +0000896 else:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000897 try:
898 f = open(file, 'r')
899 except IOError, msg:
900 print file, ":", msg
901 sys.exit(1)
Guido van Rossuma219efa1997-11-18 15:09:54 +0000902
903 data = f.read()
904 if f is not sys.stdin:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000905 f.close()
Guido van Rossuma219efa1997-11-18 15:09:54 +0000906
907 x = klass()
Guido van Rossumaf5add41998-12-22 14:23:50 +0000908 t0 = time()
Guido van Rossum7e07b381998-04-03 16:02:39 +0000909 try:
Guido van Rossumaf5add41998-12-22 14:23:50 +0000910 if do_time:
911 x.feed(data)
912 x.close()
913 else:
914 for c in data:
915 x.feed(c)
916 x.close()
Sjoerd Mullenderf7e84e12000-12-06 10:37:57 +0000917 except Error, msg:
Guido van Rossumaf5add41998-12-22 14:23:50 +0000918 t1 = time()
Guido van Rossum7e07b381998-04-03 16:02:39 +0000919 print msg
Guido van Rossumaf5add41998-12-22 14:23:50 +0000920 if do_time:
921 print 'total time: %g' % (t1-t0)
Guido van Rossum7e07b381998-04-03 16:02:39 +0000922 sys.exit(1)
Guido van Rossumaf5add41998-12-22 14:23:50 +0000923 t1 = time()
924 if do_time:
925 print 'total time: %g' % (t1-t0)
Guido van Rossuma219efa1997-11-18 15:09:54 +0000926
927
928if __name__ == '__main__':
929 test()