xmllib.py 34 KB
Newer Older
1 2
"""A parser for XML, using the derived class as static DTD."""

3
# Author: Sjoerd Mullender.
4 5 6 7

import re
import string

8
import warnings
9
warnings.warn("The xmllib module is obsolete.  Use xml.sax instead.", DeprecationWarning)
10
del warnings
11

12
version = '0.3'
Guido van Rossum's avatar
Guido van Rossum committed
13

Sjoerd Mullender's avatar
Sjoerd Mullender committed
14 15 16
class Error(RuntimeError):
    pass

17 18
# Regular expressions used for parsing

19 20 21 22
_S = '[ \t\r\n]+'                       # white space
_opS = '[ \t\r\n]*'                     # optional white space
_Name = '[a-zA-Z_:][-a-zA-Z0-9._:]*'    # valid XML name
_QStr = "(?:'[^']*'|\"[^\"]*\")"        # quoted XML string
Guido van Rossum's avatar
Guido van Rossum committed
23 24 25 26 27
illegal = re.compile('[^\t\r\n -\176\240-\377]') # illegal chars in content
interesting = re.compile('[]&<]')

amp = re.compile('&')
ref = re.compile('&(' + _Name + '|#[0-9]+|#x[0-9a-fA-F]+)[^-a-zA-Z0-9._:]')
28 29
entityref = re.compile('&(?P<name>' + _Name + ')[^-a-zA-Z0-9._:]')
charref = re.compile('&#(?P<char>[0-9]+[^0-9]|x[0-9a-fA-F]+[^0-9a-fA-F])')
Guido van Rossum's avatar
Guido van Rossum committed
30
space = re.compile(_S + '$')
31 32
newline = re.compile('\n')

33 34 35
attrfind = re.compile(
    _S + '(?P<name>' + _Name + ')'
    '(' + _opS + '=' + _opS +
Guido van Rossum's avatar
Guido van Rossum committed
36
    '(?P<value>'+_QStr+'|[-a-zA-Z0-9.:+*%?!\(\)_#=~]+))?')
37 38
starttagopen = re.compile('<' + _Name)
starttagend = re.compile(_opS + '(?P<slash>/?)>')
39 40 41 42
starttagmatch = re.compile('<(?P<tagname>'+_Name+')'
                      '(?P<attrs>(?:'+attrfind.pattern+')*)'+
                      starttagend.pattern)
endtagopen = re.compile('</')
Guido van Rossum's avatar
Guido van Rossum committed
43
endbracket = re.compile(_opS + '>')
44
endbracketfind = re.compile('(?:[^>\'"]|'+_QStr+')*>')
45
tagfind = re.compile(_Name)
46 47
cdataopen = re.compile(r'<!\[CDATA\[')
cdataclose = re.compile(r'\]\]>')
Guido van Rossum's avatar
Guido van Rossum committed
48 49 50
# this matches one of the following:
# SYSTEM SystemLiteral
# PUBLIC PubidLiteral SystemLiteral
51
_SystemLiteral = '(?P<%s>'+_QStr+')'
Guido van Rossum's avatar
Guido van Rossum committed
52 53
_PublicLiteral = '(?P<%s>"[-\'\(\)+,./:=?;!*#@$_%% \n\ra-zA-Z0-9]*"|' \
                        "'[-\(\)+,./:=?;!*#@$_%% \n\ra-zA-Z0-9]*')"
Guido van Rossum's avatar
Guido van Rossum committed
54 55 56 57 58 59
_ExternalId = '(?:SYSTEM|' \
                 'PUBLIC'+_S+_PublicLiteral%'pubid'+ \
              ')'+_S+_SystemLiteral%'syslit'
doctype = re.compile('<!DOCTYPE'+_S+'(?P<name>'+_Name+')'
                     '(?:'+_S+_ExternalId+')?'+_opS)
xmldecl = re.compile('<\?xml'+_S+
60
                     'version'+_opS+'='+_opS+'(?P<version>'+_QStr+')'+
Guido van Rossum's avatar
Guido van Rossum committed
61 62 63 64 65 66 67
                     '(?:'+_S+'encoding'+_opS+'='+_opS+
                        "(?P<encoding>'[A-Za-z][-A-Za-z0-9._]*'|"
                        '"[A-Za-z][-A-Za-z0-9._]*"))?'
                     '(?:'+_S+'standalone'+_opS+'='+_opS+
                        '(?P<standalone>\'(?:yes|no)\'|"(?:yes|no)"))?'+
                     _opS+'\?>')
procopen = re.compile(r'<\?(?P<proc>' + _Name + ')' + _opS)
68
procclose = re.compile(_opS + r'\?>')
69 70 71
commentopen = re.compile('<!--')
commentclose = re.compile('-->')
doubledash = re.compile('--')
Guido van Rossum's avatar
Guido van Rossum committed
72
attrtrans = string.maketrans(' \r\n\t', '    ')
73

74 75 76 77 78 79 80
# definitions for XML namespaces
_NCName = '[a-zA-Z_][-a-zA-Z0-9._]*'    # XML Name, minus the ":"
ncname = re.compile(_NCName + '$')
qname = re.compile('(?:(?P<prefix>' + _NCName + '):)?' # optional prefix
                   '(?P<local>' + _NCName + ')$')

xmlns = re.compile('xmlns(?::(?P<ncname>'+_NCName+'))?$')
81 82 83

# XML parser base class -- find tags and call handler functions.
# Usage: p = XMLParser(); p.feed(data); ...; p.close().
84 85 86 87
# The dtd is defined by deriving a class which defines methods with
# special names to handle tags: start_foo and end_foo to handle <foo>
# and </foo>, respectively.  The data between tags is passed to the
# parser by calling self.handle_data() with some data as argument (the
Jeremy Hylton's avatar
Jeremy Hylton committed
88
# data may be split up in arbitrary chunks).
89 90

class XMLParser:
91 92
    attributes = {}                     # default, to be overridden
    elements = {}                       # default, to be overridden
93

94 95 96 97 98
    # parsing options, settable using keyword args in __init__
    __accept_unquoted_attributes = 0
    __accept_missing_endtag_name = 0
    __map_case = 0
    __accept_utf8 = 0
99
    __translate_attribute_references = 1
100

101
    # Interface -- initialize and reset this instance
102
    def __init__(self, **kw):
103
        self.__fixed = 0
104
        if 'accept_unquoted_attributes' in kw:
105
            self.__accept_unquoted_attributes = kw['accept_unquoted_attributes']
106
        if 'accept_missing_endtag_name' in kw:
107
            self.__accept_missing_endtag_name = kw['accept_missing_endtag_name']
108
        if 'map_case' in kw:
109
            self.__map_case = kw['map_case']
110
        if 'accept_utf8' in kw:
111
            self.__accept_utf8 = kw['accept_utf8']
112
        if 'translate_attribute_references' in kw:
113
            self.__translate_attribute_references = kw['translate_attribute_references']
114
        self.reset()
115 116

    def __fixelements(self):
117
        self.__fixed = 1
118 119 120 121 122 123 124 125 126 127
        self.elements = {}
        self.__fixdict(self.__dict__)
        self.__fixclass(self.__class__)

    def __fixclass(self, kl):
        self.__fixdict(kl.__dict__)
        for k in kl.__bases__:
            self.__fixclass(k)

    def __fixdict(self, dict):
128
        for key in dict.keys():
129
            if key[:6] == 'start_':
130 131
                tag = key[6:]
                start, end = self.elements.get(tag, (None, None))
132
                if start is None:
133
                    self.elements[tag] = getattr(self, key), end
134
            elif key[:4] == 'end_':
135 136
                tag = key[4:]
                start, end = self.elements.get(tag, (None, None))
137
                if end is None:
138
                    self.elements[tag] = start, getattr(self, key)
139 140 141

    # Interface -- reset this instance.  Loses all unprocessed data
    def reset(self):
142 143 144 145 146 147 148 149
        self.rawdata = ''
        self.stack = []
        self.nomoretags = 0
        self.literal = 0
        self.lineno = 1
        self.__at_start = 1
        self.__seen_doctype = None
        self.__seen_starttag = 0
Guido van Rossum's avatar
Guido van Rossum committed
150
        self.__use_namespaces = 0
151
        self.__namespaces = {'xml':None}   # xml is implicitly declared
152
        # backward compatibility hack: if elements not overridden,
153 154 155
        # fill it in ourselves
        if self.elements is XMLParser.elements:
            self.__fixelements()
156 157 158

    # For derived classes only -- enter literal mode (CDATA) till EOF
    def setnomoretags(self):
159
        self.nomoretags = self.literal = 1
160 161 162

    # For derived classes only -- enter literal mode (CDATA)
    def setliteral(self, *args):
163
        self.literal = 1
164 165 166 167 168 169

    # Interface -- feed some data to the parser.  Call this as
    # often as you want, with as little or as much text as you
    # want (may include '\n').  (This just saves the text, all the
    # processing is done by goahead().)
    def feed(self, data):
170 171
        self.rawdata = self.rawdata + data
        self.goahead(0)
172 173 174

    # Interface -- handle the remaining data
    def close(self):
175
        self.goahead(1)
176 177 178 179
        if self.__fixed:
            self.__fixed = 0
            # remove self.elements so that we don't leak
            del self.elements
180 181

    # Interface -- translate references
Guido van Rossum's avatar
Guido van Rossum committed
182
    def translate_references(self, data, all = 1):
183 184
        if not self.__translate_attribute_references:
            return data
185 186
        i = 0
        while 1:
Guido van Rossum's avatar
Guido van Rossum committed
187
            res = amp.search(data, i)
188
            if res is None:
Guido van Rossum's avatar
Guido van Rossum committed
189
                return data
190 191
            s = res.start(0)
            res = ref.match(data, s)
Guido van Rossum's avatar
Guido van Rossum committed
192 193
            if res is None:
                self.syntax_error("bogus `&'")
194
                i = s+1
Guido van Rossum's avatar
Guido van Rossum committed
195 196
                continue
            i = res.end(0)
197
            str = res.group(1)
198
            rescan = 0
199 200
            if str[0] == '#':
                if str[1] == 'x':
201
                    str = chr(int(str[2:], 16))
202
                else:
203
                    str = chr(int(str[1:]))
204 205 206
                if data[i - 1] != ';':
                    self.syntax_error("`;' missing after char reference")
                    i = i-1
Guido van Rossum's avatar
Guido van Rossum committed
207
            elif all:
208
                if str in self.entitydefs:
209 210 211 212 213 214
                    str = self.entitydefs[str]
                    rescan = 1
                elif data[i - 1] != ';':
                    self.syntax_error("bogus `&'")
                    i = s + 1 # just past the &
                    continue
Guido van Rossum's avatar
Guido van Rossum committed
215
                else:
216
                    self.syntax_error("reference to unknown entity `&%s;'" % str)
217 218 219 220 221 222 223 224 225 226 227
                    str = '&' + str + ';'
            elif data[i - 1] != ';':
                self.syntax_error("bogus `&'")
                i = s + 1 # just past the &
                continue

            # when we get here, str contains the translated text and i points
            # to the end of the string that is to be replaced
            data = data[:s] + str + data[i:]
            if rescan:
                i = s
Guido van Rossum's avatar
Guido van Rossum committed
228
            else:
229
                i = s + len(str)
230

231 232 233 234 235 236 237
    # Interface - return a dictionary of all namespaces currently valid
    def getnamespace(self):
        nsdict = {}
        for t, d, nst in self.stack:
            nsdict.update(d)
        return nsdict

238 239 240 241
    # Internal -- handle data as far as reasonable.  May leave state
    # and data to be processed by a subsequent call.  If 'end' is
    # true, force handling all data as if followed by EOF marker.
    def goahead(self, end):
242 243 244 245 246 247 248 249 250
        rawdata = self.rawdata
        i = 0
        n = len(rawdata)
        while i < n:
            if i > 0:
                self.__at_start = 0
            if self.nomoretags:
                data = rawdata[i:n]
                self.handle_data(data)
251
                self.lineno = self.lineno + data.count('\n')
252 253 254 255
                i = n
                break
            res = interesting.search(rawdata, i)
            if res:
256
                j = res.start(0)
257
            else:
258
                j = n
259
            if i < j:
Guido van Rossum's avatar
Guido van Rossum committed
260 261
                data = rawdata[i:j]
                if self.__at_start and space.match(data) is None:
Guido van Rossum's avatar
Guido van Rossum committed
262
                    self.syntax_error('illegal data at start of file')
263
                self.__at_start = 0
264
                if not self.stack and space.match(data) is None:
Guido van Rossum's avatar
Guido van Rossum committed
265
                    self.syntax_error('data not in content')
266
                if not self.__accept_utf8 and illegal.search(data):
Guido van Rossum's avatar
Guido van Rossum committed
267
                    self.syntax_error('illegal character in content')
268
                self.handle_data(data)
269
                self.lineno = self.lineno + data.count('\n')
270 271 272 273 274 275 276
            i = j
            if i == n: break
            if rawdata[i] == '<':
                if starttagopen.match(rawdata, i):
                    if self.literal:
                        data = rawdata[i]
                        self.handle_data(data)
277
                        self.lineno = self.lineno + data.count('\n')
278 279 280 281 282
                        i = i+1
                        continue
                    k = self.parse_starttag(i)
                    if k < 0: break
                    self.__seen_starttag = 1
283
                    self.lineno = self.lineno + rawdata[i:k].count('\n')
284 285 286 287 288
                    i = k
                    continue
                if endtagopen.match(rawdata, i):
                    k = self.parse_endtag(i)
                    if k < 0: break
289
                    self.lineno = self.lineno + rawdata[i:k].count('\n')
290 291 292 293 294 295
                    i =  k
                    continue
                if commentopen.match(rawdata, i):
                    if self.literal:
                        data = rawdata[i]
                        self.handle_data(data)
296
                        self.lineno = self.lineno + data.count('\n')
297 298 299 300
                        i = i+1
                        continue
                    k = self.parse_comment(i)
                    if k < 0: break
301
                    self.lineno = self.lineno + rawdata[i:k].count('\n')
302 303 304 305 306
                    i = k
                    continue
                if cdataopen.match(rawdata, i):
                    k = self.parse_cdata(i)
                    if k < 0: break
307
                    self.lineno = self.lineno + rawdata[i:k].count('\n')
308 309
                    i = k
                    continue
Guido van Rossum's avatar
Guido van Rossum committed
310 311 312 313 314 315 316 317
                res = xmldecl.match(rawdata, i)
                if res:
                    if not self.__at_start:
                        self.syntax_error("<?xml?> declaration not at start of document")
                    version, encoding, standalone = res.group('version',
                                                              'encoding',
                                                              'standalone')
                    if version[1:-1] != '1.0':
Sjoerd Mullender's avatar
Sjoerd Mullender committed
318
                        raise Error('only XML version 1.0 supported')
Guido van Rossum's avatar
Guido van Rossum committed
319 320 321 322 323
                    if encoding: encoding = encoding[1:-1]
                    if standalone: standalone = standalone[1:-1]
                    self.handle_xml(encoding, standalone)
                    i = res.end(0)
                    continue
324 325 326 327
                res = procopen.match(rawdata, i)
                if res:
                    k = self.parse_proc(i)
                    if k < 0: break
328
                    self.lineno = self.lineno + rawdata[i:k].count('\n')
329 330 331 332 333 334 335
                    i = k
                    continue
                res = doctype.match(rawdata, i)
                if res:
                    if self.literal:
                        data = rawdata[i]
                        self.handle_data(data)
336
                        self.lineno = self.lineno + data.count('\n')
337 338 339 340 341 342 343 344 345
                        i = i+1
                        continue
                    if self.__seen_doctype:
                        self.syntax_error('multiple DOCTYPE elements')
                    if self.__seen_starttag:
                        self.syntax_error('DOCTYPE not at beginning of document')
                    k = self.parse_doctype(res)
                    if k < 0: break
                    self.__seen_doctype = res.group('name')
346
                    if self.__map_case:
347 348
                        self.__seen_doctype = self.__seen_doctype.lower()
                    self.lineno = self.lineno + rawdata[i:k].count('\n')
349 350 351
                    i = k
                    continue
            elif rawdata[i] == '&':
352 353 354 355 356
                if self.literal:
                    data = rawdata[i]
                    self.handle_data(data)
                    i = i+1
                    continue
357 358 359 360 361 362
                res = charref.match(rawdata, i)
                if res is not None:
                    i = res.end(0)
                    if rawdata[i-1] != ';':
                        self.syntax_error("`;' missing in charref")
                        i = i-1
Guido van Rossum's avatar
Guido van Rossum committed
363 364
                    if not self.stack:
                        self.syntax_error('data not in content')
365
                    self.handle_charref(res.group('char')[:-1])
366
                    self.lineno = self.lineno + res.group(0).count('\n')
367 368 369 370 371 372 373
                    continue
                res = entityref.match(rawdata, i)
                if res is not None:
                    i = res.end(0)
                    if rawdata[i-1] != ';':
                        self.syntax_error("`;' missing in entityref")
                        i = i-1
Guido van Rossum's avatar
Guido van Rossum committed
374
                    name = res.group('name')
375
                    if self.__map_case:
376
                        name = name.lower()
377
                    if name in self.entitydefs:
Guido van Rossum's avatar
Guido van Rossum committed
378 379 380 381 382
                        self.rawdata = rawdata = rawdata[:res.start(0)] + self.entitydefs[name] + rawdata[i:]
                        n = len(rawdata)
                        i = res.start(0)
                    else:
                        self.unknown_entityref(name)
383
                    self.lineno = self.lineno + res.group(0).count('\n')
384
                    continue
Guido van Rossum's avatar
Guido van Rossum committed
385
            elif rawdata[i] == ']':
386 387 388 389 390
                if self.literal:
                    data = rawdata[i]
                    self.handle_data(data)
                    i = i+1
                    continue
Guido van Rossum's avatar
Guido van Rossum committed
391 392 393 394 395 396 397
                if n-i < 3:
                    break
                if cdataclose.match(rawdata, i):
                    self.syntax_error("bogus `]]>'")
                self.handle_data(rawdata[i])
                i = i+1
                continue
398
            else:
Sjoerd Mullender's avatar
Sjoerd Mullender committed
399
                raise Error('neither < nor & ??')
400 401
            # We get here only if incomplete matches but
            # nothing else
Guido van Rossum's avatar
Guido van Rossum committed
402
            break
403
        # end while
Guido van Rossum's avatar
Guido van Rossum committed
404 405
        if i > 0:
            self.__at_start = 0
406
        if end and i < n:
Guido van Rossum's avatar
Guido van Rossum committed
407 408
            data = rawdata[i]
            self.syntax_error("bogus `%s'" % data)
409
            if not self.__accept_utf8 and illegal.search(data):
Guido van Rossum's avatar
Guido van Rossum committed
410
                self.syntax_error('illegal character in content')
411
            self.handle_data(data)
412
            self.lineno = self.lineno + data.count('\n')
Guido van Rossum's avatar
Guido van Rossum committed
413 414
            self.rawdata = rawdata[i+1:]
            return self.goahead(end)
415 416
        self.rawdata = rawdata[i:]
        if end:
Guido van Rossum's avatar
Guido van Rossum committed
417 418
            if not self.__seen_starttag:
                self.syntax_error('no elements in file')
419 420 421
            if self.stack:
                self.syntax_error('missing end tags')
                while self.stack:
422
                    self.finish_endtag(self.stack[-1][0])
423 424 425

    # Internal -- parse comment, return length or -1 if not terminated
    def parse_comment(self, i):
426
        rawdata = self.rawdata
427
        if rawdata[i:i+4] != '<!--':
Sjoerd Mullender's avatar
Sjoerd Mullender committed
428
            raise Error('unexpected call to handle_comment')
429
        res = commentclose.search(rawdata, i+4)
430
        if res is None:
431
            return -1
Guido van Rossum's avatar
Guido van Rossum committed
432
        if doubledash.search(rawdata, i+4, res.start(0)):
433
            self.syntax_error("`--' inside comment")
Guido van Rossum's avatar
Guido van Rossum committed
434 435
        if rawdata[res.start(0)-1] == '-':
            self.syntax_error('comment cannot end in three dashes')
436 437
        if not self.__accept_utf8 and \
           illegal.search(rawdata, i+4, res.start(0)):
Guido van Rossum's avatar
Guido van Rossum committed
438
            self.syntax_error('illegal character in comment')
439 440
        self.handle_comment(rawdata[i+4: res.start(0)])
        return res.end(0)
441

442 443
    # Internal -- handle DOCTYPE tag, return length or -1 if not terminated
    def parse_doctype(self, res):
444 445 446
        rawdata = self.rawdata
        n = len(rawdata)
        name = res.group('name')
447
        if self.__map_case:
448
            name = name.lower()
Guido van Rossum's avatar
Guido van Rossum committed
449 450 451
        pubid, syslit = res.group('pubid', 'syslit')
        if pubid is not None:
            pubid = pubid[1:-1]         # remove quotes
452
            pubid = ' '.join(pubid.split()) # normalize
Guido van Rossum's avatar
Guido van Rossum committed
453
        if syslit is not None: syslit = syslit[1:-1] # remove quotes
454
        j = k = res.end(0)
Guido van Rossum's avatar
Guido van Rossum committed
455 456 457 458
        if k >= n:
            return -1
        if rawdata[k] == '[':
            level = 0
459
            k = k+1
Guido van Rossum's avatar
Guido van Rossum committed
460 461 462 463 464 465 466 467 468 469 470
            dq = sq = 0
            while k < n:
                c = rawdata[k]
                if not sq and c == '"':
                    dq = not dq
                elif not dq and c == "'":
                    sq = not sq
                elif sq or dq:
                    pass
                elif level <= 0 and c == ']':
                    res = endbracket.match(rawdata, k+1)
471
                    if res is None:
Guido van Rossum's avatar
Guido van Rossum committed
472 473 474 475 476 477 478 479 480 481
                        return -1
                    self.handle_doctype(name, pubid, syslit, rawdata[j+1:k])
                    return res.end(0)
                elif c == '<':
                    level = level + 1
                elif c == '>':
                    level = level - 1
                    if level < 0:
                        self.syntax_error("bogus `>' in DOCTYPE")
                k = k+1
482 483
        res = endbracketfind.match(rawdata, k)
        if res is None:
Guido van Rossum's avatar
Guido van Rossum committed
484
            return -1
485
        if endbracket.match(rawdata, k) is None:
Guido van Rossum's avatar
Guido van Rossum committed
486 487 488
            self.syntax_error('garbage in DOCTYPE')
        self.handle_doctype(name, pubid, syslit, None)
        return res.end(0)
489 490

    # Internal -- handle CDATA tag, return length or -1 if not terminated
491
    def parse_cdata(self, i):
492
        rawdata = self.rawdata
493
        if rawdata[i:i+9] != '<![CDATA[':
Sjoerd Mullender's avatar
Sjoerd Mullender committed
494
            raise Error('unexpected call to parse_cdata')
495
        res = cdataclose.search(rawdata, i+9)
496
        if res is None:
497
            return -1
498 499
        if not self.__accept_utf8 and \
           illegal.search(rawdata, i+9, res.start(0)):
Guido van Rossum's avatar
Guido van Rossum committed
500 501 502
            self.syntax_error('illegal character in CDATA')
        if not self.stack:
            self.syntax_error('CDATA not in content')
503 504
        self.handle_cdata(rawdata[i+9:res.start(0)])
        return res.end(0)
505

506
    __xml_namespace_attributes = {'ns':None, 'src':None, 'prefix':None}
507 508
    # Internal -- handle a processing instruction tag
    def parse_proc(self, i):
509 510
        rawdata = self.rawdata
        end = procclose.search(rawdata, i)
511
        if end is None:
512 513
            return -1
        j = end.start(0)
514
        if not self.__accept_utf8 and illegal.search(rawdata, i+2, j):
Guido van Rossum's avatar
Guido van Rossum committed
515
            self.syntax_error('illegal character in processing instruction')
516
        res = tagfind.match(rawdata, i+2)
517
        if res is None:
Sjoerd Mullender's avatar
Sjoerd Mullender committed
518
            raise Error('unexpected call to parse_proc')
519 520
        k = res.end(0)
        name = res.group(0)
521
        if self.__map_case:
522
            name = name.lower()
523 524
        if name == 'xml:namespace':
            self.syntax_error('old-fashioned namespace declaration')
Guido van Rossum's avatar
Guido van Rossum committed
525
            self.__use_namespaces = -1
526 527 528 529 530 531 532 533 534
            # namespace declaration
            # this must come after the <?xml?> declaration (if any)
            # and before the <!DOCTYPE> (if any).
            if self.__seen_doctype or self.__seen_starttag:
                self.syntax_error('xml:namespace declaration too late in document')
            attrdict, namespace, k = self.parse_attributes(name, k, j)
            if namespace:
                self.syntax_error('namespace declaration inside namespace declaration')
            for attrname in attrdict.keys():
535
                if not attrname in self.__xml_namespace_attributes:
536
                    self.syntax_error("unknown attribute `%s' in xml:namespace tag" % attrname)
537
            if not 'ns' in attrdict or not 'prefix' in attrdict:
538 539 540 541 542
                self.syntax_error('xml:namespace without required attributes')
            prefix = attrdict.get('prefix')
            if ncname.match(prefix) is None:
                self.syntax_error('xml:namespace illegal prefix value')
                return end.end(0)
543
            if prefix in self.__namespaces:
544 545 546
                self.syntax_error('xml:namespace prefix not unique')
            self.__namespaces[prefix] = attrdict['ns']
        else:
547
            if name.lower() == 'xml':
548 549
                self.syntax_error('illegal processing instruction target name')
            self.handle_proc(name, rawdata[k:j])
550
        return end.end(0)
551 552

    # Internal -- parse attributes between i and j
553
    def parse_attributes(self, tag, i, j):
554 555
        rawdata = self.rawdata
        attrdict = {}
556
        namespace = {}
557 558 559 560
        while i < j:
            res = attrfind.match(rawdata, i)
            if res is None:
                break
561
            attrname, attrvalue = res.group('name', 'value')
562
            if self.__map_case:
563
                attrname = attrname.lower()
564
            i = res.end(0)
565
            if attrvalue is None:
566
                self.syntax_error("no value specified for attribute `%s'" % attrname)
567 568 569 570
                attrvalue = attrname
            elif attrvalue[:1] == "'" == attrvalue[-1:] or \
                 attrvalue[:1] == '"' == attrvalue[-1:]:
                attrvalue = attrvalue[1:-1]
571
            elif not self.__accept_unquoted_attributes:
572
                self.syntax_error("attribute `%s' value not quoted" % attrname)
573 574 575 576 577
            res = xmlns.match(attrname)
            if res is not None:
                # namespace declaration
                ncname = res.group('ncname')
                namespace[ncname or ''] = attrvalue or None
Guido van Rossum's avatar
Guido van Rossum committed
578 579
                if not self.__use_namespaces:
                    self.__use_namespaces = len(self.stack)+1
580
                continue
581 582
            if '<' in attrvalue:
                self.syntax_error("`<' illegal in attribute value")
583
            if attrname in attrdict:
584
                self.syntax_error("attribute `%s' specified twice" % attrname)
585
            attrvalue = attrvalue.translate(attrtrans)
586
            attrdict[attrname] = self.translate_references(attrvalue)
587
        return attrdict, namespace, i
588 589 590

    # Internal -- handle starttag, return length or -1 if not terminated
    def parse_starttag(self, i):
591 592
        rawdata = self.rawdata
        # i points to start of tag
593 594
        end = endbracketfind.match(rawdata, i+1)
        if end is None:
595
            return -1
596 597 598 599
        tag = starttagmatch.match(rawdata, i)
        if tag is None or tag.end(0) != end.end(0):
            self.syntax_error('garbage in starttag')
            return end.end(0)
600
        nstag = tagname = tag.group('tagname')
601
        if self.__map_case:
602
            nstag = tagname = nstag.lower()
603 604 605
        if not self.__seen_starttag and self.__seen_doctype and \
           tagname != self.__seen_doctype:
            self.syntax_error('starttag does not match DOCTYPE')
Guido van Rossum's avatar
Guido van Rossum committed
606 607
        if self.__seen_starttag and not self.stack:
            self.syntax_error('multiple elements on top level')
608
        k, j = tag.span('attrs')
609 610
        attrdict, nsdict, k = self.parse_attributes(tagname, k, j)
        self.stack.append((tagname, nsdict, nstag))
Guido van Rossum's avatar
Guido van Rossum committed
611 612 613 614
        if self.__use_namespaces:
            res = qname.match(tagname)
        else:
            res = None
615 616 617 618 619 620
        if res is not None:
            prefix, nstag = res.group('prefix', 'local')
            if prefix is None:
                prefix = ''
            ns = None
            for t, d, nst in self.stack:
621
                if prefix in d:
622 623 624 625 626 627 628 629 630
                    ns = d[prefix]
            if ns is None and prefix != '':
                ns = self.__namespaces.get(prefix)
            if ns is not None:
                nstag = ns + ' ' + nstag
            elif prefix != '':
                nstag = prefix + ':' + nstag # undo split
            self.stack[-1] = tagname, nsdict, nstag
        # translate namespace of attributes
Sjoerd Mullender's avatar
Sjoerd Mullender committed
631 632 633
        attrnamemap = {} # map from new name to old name (used for error reporting)
        for key in attrdict.keys():
            attrnamemap[key] = key
Guido van Rossum's avatar
Guido van Rossum committed
634 635 636
        if self.__use_namespaces:
            nattrdict = {}
            for key, val in attrdict.items():
Sjoerd Mullender's avatar
Sjoerd Mullender committed
637
                okey = key
Guido van Rossum's avatar
Guido van Rossum committed
638 639 640
                res = qname.match(key)
                if res is not None:
                    aprefix, key = res.group('prefix', 'local')
641
                    if self.__map_case:
642
                        key = key.lower()
643 644 645 646 647 648 649 650 651 652 653
                    if aprefix is not None:
                        ans = None
                        for t, d, nst in self.stack:
                            if aprefix in d:
                                ans = d[aprefix]
                        if ans is None:
                            ans = self.__namespaces.get(aprefix)
                        if ans is not None:
                            key = ans + ' ' + key
                        else:
                            key = aprefix + ':' + key
Guido van Rossum's avatar
Guido van Rossum committed
654
                nattrdict[key] = val
Sjoerd Mullender's avatar
Sjoerd Mullender committed
655
                attrnamemap[key] = okey
Guido van Rossum's avatar
Guido van Rossum committed
656
            attrdict = nattrdict
657 658 659
        attributes = self.attributes.get(nstag)
        if attributes is not None:
            for key in attrdict.keys():
660
                if not key in attributes:
Sjoerd Mullender's avatar
Sjoerd Mullender committed
661
                    self.syntax_error("unknown attribute `%s' in tag `%s'" % (attrnamemap[key], tagname))
662
            for key, val in attributes.items():
663
                if val is not None and not key in attrdict:
664 665 666
                    attrdict[key] = val
        method = self.elements.get(nstag, (None, None))[0]
        self.finish_starttag(nstag, attrdict, method)
667 668 669
        if tag.group('slash') == '/':
            self.finish_endtag(tagname)
        return tag.end(0)
670 671 672

    # Internal -- parse endtag
    def parse_endtag(self, i):
673
        rawdata = self.rawdata
674 675
        end = endbracketfind.match(rawdata, i+1)
        if end is None:
676 677
            return -1
        res = tagfind.match(rawdata, i+2)
678
        if res is None:
Guido van Rossum's avatar
Guido van Rossum committed
679 680 681
            if self.literal:
                self.handle_data(rawdata[i])
                return i+1
682 683
            if not self.__accept_missing_endtag_name:
                self.syntax_error('no name specified in end tag')
Guido van Rossum's avatar
Guido van Rossum committed
684
            tag = self.stack[-1][0]
685 686 687
            k = i+2
        else:
            tag = res.group(0)
688
            if self.__map_case:
689
                tag = tag.lower()
Guido van Rossum's avatar
Guido van Rossum committed
690
            if self.literal:
691
                if not self.stack or tag != self.stack[-1][0]:
Guido van Rossum's avatar
Guido van Rossum committed
692 693
                    self.handle_data(rawdata[i])
                    return i+1
694
            k = res.end(0)
695
        if endbracket.match(rawdata, k) is None:
Guido van Rossum's avatar
Guido van Rossum committed
696
            self.syntax_error('garbage in end tag')
697 698
        self.finish_endtag(tag)
        return end.end(0)
699 700

    # Internal -- finish processing of start tag
701 702 703
    def finish_starttag(self, tagname, attrdict, method):
        if method is not None:
            self.handle_starttag(tagname, method, attrdict)
Guido van Rossum's avatar
Guido van Rossum committed
704
        else:
705
            self.unknown_starttag(tagname, attrdict)
706 707 708

    # Internal -- finish processing of end tag
    def finish_endtag(self, tag):
709
        self.literal = 0
710 711 712 713 714 715 716
        if not tag:
            self.syntax_error('name-less end tag')
            found = len(self.stack) - 1
            if found < 0:
                self.unknown_endtag(tag)
                return
        else:
717 718 719 720 721
            found = -1
            for i in range(len(self.stack)):
                if tag == self.stack[i][0]:
                    found = i
            if found == -1:
722 723 724 725
                self.syntax_error('unopened end tag')
                return
        while len(self.stack) > found:
            if found < len(self.stack) - 1:
726 727 728 729 730
                self.syntax_error('missing close tag for %s' % self.stack[-1][2])
            nstag = self.stack[-1][2]
            method = self.elements.get(nstag, (None, None))[1]
            if method is not None:
                self.handle_endtag(nstag, method)
731
            else:
732
                self.unknown_endtag(nstag)
Guido van Rossum's avatar
Guido van Rossum committed
733 734
            if self.__use_namespaces == len(self.stack):
                self.__use_namespaces = 0
735
            del self.stack[-1]
736

737 738
    # Overridable -- handle xml processing instruction
    def handle_xml(self, encoding, standalone):
739
        pass
740 741

    # Overridable -- handle DOCTYPE
Guido van Rossum's avatar
Guido van Rossum committed
742
    def handle_doctype(self, tag, pubid, syslit, data):
743
        pass
744

745 746
    # Overridable -- handle start tag
    def handle_starttag(self, tag, method, attrs):
747
        method(attrs)
748 749 750

    # Overridable -- handle end tag
    def handle_endtag(self, tag, method):
751
        method()
752 753 754

    # Example -- handle character reference, no need to override
    def handle_charref(self, name):
755 756
        try:
            if name[0] == 'x':
757
                n = int(name[1:], 16)
758
            else:
759 760
                n = int(name)
        except ValueError:
761 762 763 764 765 766
            self.unknown_charref(name)
            return
        if not 0 <= n <= 255:
            self.unknown_charref(name)
            return
        self.handle_data(chr(n))
767 768

    # Definition of entities -- derived classes may override
Guido van Rossum's avatar
Guido van Rossum committed
769 770 771 772 773 774
    entitydefs = {'lt': '&#60;',        # must use charref
                  'gt': '&#62;',
                  'amp': '&#38;',       # must use charref
                  'quot': '&#34;',
                  'apos': '&#39;',
                  }
775 776 777

    # Example -- handle data, should be overridden
    def handle_data(self, data):
778
        pass
779 780 781

    # Example -- handle cdata, could be overridden
    def handle_cdata(self, data):
782
        pass
783 784 785

    # Example -- handle comment, could be overridden
    def handle_comment(self, data):
786
        pass
787 788 789

    # Example -- handle processing instructions, could be overridden
    def handle_proc(self, name, data):
790
        pass
791 792

    # Example -- handle relatively harmless syntax errors, could be overridden
793
    def syntax_error(self, message):
Sjoerd Mullender's avatar
Sjoerd Mullender committed
794
        raise Error('Syntax error at line %d: %s' % (self.lineno, message))
795 796 797 798 799

    # To be overridden -- handlers for unknown objects
    def unknown_starttag(self, tag, attrs): pass
    def unknown_endtag(self, tag): pass
    def unknown_charref(self, ref): pass
800 801
    def unknown_entityref(self, name):
        self.syntax_error("reference to unknown entity `&%s;'" % name)
802 803 804 805


class TestXMLParser(XMLParser):

806
    def __init__(self, **kw):
807
        self.testdata = ""
808
        XMLParser.__init__(self, **kw)
809

810
    def handle_xml(self, encoding, standalone):
811 812
        self.flush()
        print 'xml: encoding =',encoding,'standalone =',standalone
813

Guido van Rossum's avatar
Guido van Rossum committed
814
    def handle_doctype(self, tag, pubid, syslit, data):
815
        self.flush()
816
        print 'DOCTYPE:',tag, repr(data)
817

818
    def handle_data(self, data):
819
        self.testdata = self.testdata + data
820
        if len(repr(self.testdata)) >= 70:
821
            self.flush()
822 823

    def flush(self):
824 825 826
        data = self.testdata
        if data:
            self.testdata = ""
827
            print 'data:', repr(data)
828 829

    def handle_cdata(self, data):
830
        self.flush()
831
        print 'cdata:', repr(data)
832 833

    def handle_proc(self, name, data):
834
        self.flush()
835
        print 'processing:',name,repr(data)
836 837

    def handle_comment(self, data):
838
        self.flush()
839
        r = repr(data)
840 841 842
        if len(r) > 68:
            r = r[:32] + '...' + r[-32:]
        print 'comment:', r
843

844
    def syntax_error(self, message):
845
        print 'error at line %d:' % self.lineno, message
846 847

    def unknown_starttag(self, tag, attrs):
848 849 850 851 852 853 854 855
        self.flush()
        if not attrs:
            print 'start tag: <' + tag + '>'
        else:
            print 'start tag: <' + tag,
            for name, value in attrs.items():
                print name + '=' + '"' + value + '"',
            print '>'
856 857

    def unknown_endtag(self, tag):
858 859
        self.flush()
        print 'end tag: </' + tag + '>'
860 861

    def unknown_entityref(self, ref):
862 863
        self.flush()
        print '*** unknown entity ref: &' + ref + ';'
864 865

    def unknown_charref(self, ref):
866 867
        self.flush()
        print '*** unknown char ref: &#' + ref + ';'
868 869

    def close(self):
870 871
        XMLParser.close(self)
        self.flush()
872 873

def test(args = None):
874 875
    import sys, getopt
    from time import time
876 877

    if not args:
878
        args = sys.argv[1:]
879

880 881 882 883 884 885 886 887
    opts, args = getopt.getopt(args, 'st')
    klass = TestXMLParser
    do_time = 0
    for o, a in opts:
        if o == '-s':
            klass = XMLParser
        elif o == '-t':
            do_time = 1
888 889

    if args:
890
        file = args[0]
891
    else:
892
        file = 'test.xml'
893 894

    if file == '-':
895
        f = sys.stdin
896
    else:
897 898 899 900 901
        try:
            f = open(file, 'r')
        except IOError, msg:
            print file, ":", msg
            sys.exit(1)
902 903 904

    data = f.read()
    if f is not sys.stdin:
905
        f.close()
906 907

    x = klass()
908
    t0 = time()
Guido van Rossum's avatar
Guido van Rossum committed
909
    try:
910 911 912 913 914 915 916
        if do_time:
            x.feed(data)
            x.close()
        else:
            for c in data:
                x.feed(c)
            x.close()
Sjoerd Mullender's avatar
Sjoerd Mullender committed
917
    except Error, msg:
918
        t1 = time()
Guido van Rossum's avatar
Guido van Rossum committed
919
        print msg
920 921
        if do_time:
            print 'total time: %g' % (t1-t0)
Guido van Rossum's avatar
Guido van Rossum committed
922
        sys.exit(1)
923 924 925
    t1 = time()
    if do_time:
        print 'total time: %g' % (t1-t0)
926 927 928 929


if __name__ == '__main__':
    test()