blob: 2f1ff1c9cfe1c85120356c6590a561a3f48eb151 [file] [log] [blame]
Fred Drake45cd9de2000-06-29 19:34:54 +00001"""
2SAX driver for the Pyexpat C module. This driver works with
3pyexpat.__version__ == '1.5'.
Fred Drake45cd9de2000-06-29 19:34:54 +00004"""
5
6# Todo on driver:
7# - make it support external entities (wait for pyexpat.c)
8# - enable configuration between reset() and feed() calls
9# - support lexical events?
10# - proper inputsource handling
11# - properties and features
12
13# Todo on pyexpat.c:
14# - support XML_ExternalEntityParserCreate
15# - exceptions in callouts from pyexpat to python code lose position info
16
17version = "0.20"
18
Lars Gustäbelf43cf312000-09-24 18:29:24 +000019from xml.sax._exceptions import *
Fred Drake96ea1962000-09-23 04:49:30 +000020from xml.parsers import expat
Fred Drake45cd9de2000-06-29 19:34:54 +000021from xml.sax import xmlreader
Fred Drake45cd9de2000-06-29 19:34:54 +000022
Lars Gustäbel32bf12e2000-09-24 18:39:23 +000023AttributesImpl = xmlreader.AttributesImpl
24AttributesNSImpl = xmlreader.AttributesNSImpl
25
Fred Drake45cd9de2000-06-29 19:34:54 +000026# --- ExpatParser
27
Fred Drakeddb48672000-09-23 05:32:26 +000028class ExpatParser(xmlreader.IncrementalParser, xmlreader.Locator):
Fred Drake45cd9de2000-06-29 19:34:54 +000029 "SAX driver for the Pyexpat C module."
30
31 def __init__(self, namespaceHandling=0, bufsize=2**16-20):
32 xmlreader.IncrementalParser.__init__(self, bufsize)
33 self._source = None
34 self._parser = None
35 self._namespaces = namespaceHandling
36 self._parsing = 0
37
38 # XMLReader methods
39
Fred Drakeddb48672000-09-23 05:32:26 +000040 def parse(self, stream_or_string):
Skip Montanaro26a79832000-07-06 02:56:36 +000041 "Parse an XML document from a URL."
Fred Drakeddb48672000-09-23 05:32:26 +000042 if type(stream_or_string) is type(""):
43 stream = open(stream_or_string)
Fred Drake45cd9de2000-06-29 19:34:54 +000044 else:
Fred Drakeddb48672000-09-23 05:32:26 +000045 stream = stream_or_string
Fred Drake45cd9de2000-06-29 19:34:54 +000046
47 self.reset()
48 self._cont_handler.setDocumentLocator(self)
49 try:
50 xmlreader.IncrementalParser.parse(self, stream)
Fred Drake96ea1962000-09-23 04:49:30 +000051 except expat.error:
Fred Drake45cd9de2000-06-29 19:34:54 +000052 error_code = self._parser.ErrorCode
Lars Gustäbelf43cf312000-09-24 18:29:24 +000053 raise SAXParseException(expat.ErrorString(error_code), None, self)
Fred Drake45cd9de2000-06-29 19:34:54 +000054
55 self._cont_handler.endDocument()
56
57 def prepareParser(self, filename=None):
58 self._source = filename
59
60 if self._source != None:
61 self._parser.SetBase(self._source)
62
63 def getFeature(self, name):
Lars Gustäbelf43cf312000-09-24 18:29:24 +000064 if name == feature_namespaces:
65 return self._namespaces
Fred Drake45cd9de2000-06-29 19:34:54 +000066 raise SAXNotRecognizedException("Feature '%s' not recognized" % name)
67
68 def setFeature(self, name, state):
Lars Gustäbelf43cf312000-09-24 18:29:24 +000069 if self._parsing:
70 raise SAXNotSupportedException("Cannot set features while parsing")
71 if name == feature_namespaces:
72 self._namespaces = state
73 else:
74 raise SAXNotRecognizedException("Feature '%s' not recognized" %
75 name)
Fred Drake45cd9de2000-06-29 19:34:54 +000076
77 def getProperty(self, name):
Fred Drake45cd9de2000-06-29 19:34:54 +000078 raise SAXNotRecognizedException("Property '%s' not recognized" % name)
79
80 def setProperty(self, name, value):
Fred Drake45cd9de2000-06-29 19:34:54 +000081 raise SAXNotRecognizedException("Property '%s' not recognized" % name)
82
83 # IncrementalParser methods
84
85 def feed(self, data):
86 if not self._parsing:
Fred Drakeddb48672000-09-23 05:32:26 +000087 self._parsing = 1
Fred Drake45cd9de2000-06-29 19:34:54 +000088 self.reset()
89 self._cont_handler.startDocument()
Lars Gustäbelf43cf312000-09-24 18:29:24 +000090
91 if not self._parser.Parse(data, 0):
92 msg = pyexpat.ErrorString(self._parser.ErrorCode)
93 raise SAXParseException(msg, None, self)
Fred Drake45cd9de2000-06-29 19:34:54 +000094
95 def close(self):
96 if self._parsing:
97 self._cont_handler.endDocument()
Fred Drakeddb48672000-09-23 05:32:26 +000098 self._parsing = 0
Fred Drake45cd9de2000-06-29 19:34:54 +000099 self._parser.Parse("", 1)
100
101 def reset(self):
102 if self._namespaces:
Fred Drake96ea1962000-09-23 04:49:30 +0000103 self._parser = expat.ParserCreate(None, " ")
Fred Drake45cd9de2000-06-29 19:34:54 +0000104 self._parser.StartElementHandler = self.start_element_ns
105 self._parser.EndElementHandler = self.end_element_ns
106 else:
Fred Drake96ea1962000-09-23 04:49:30 +0000107 self._parser = expat.ParserCreate()
Paul Prescod6c4753f2000-07-04 03:39:33 +0000108 self._parser.StartElementHandler = self.start_element
109 self._parser.EndElementHandler = self.end_element
Fred Drake45cd9de2000-06-29 19:34:54 +0000110
111 self._parser.ProcessingInstructionHandler = \
112 self._cont_handler.processingInstruction
113 self._parser.CharacterDataHandler = self._cont_handler.characters
114 self._parser.UnparsedEntityDeclHandler = self.unparsed_entity_decl
115 self._parser.NotationDeclHandler = self.notation_decl
116 self._parser.StartNamespaceDeclHandler = self.start_namespace_decl
117 self._parser.EndNamespaceDeclHandler = self.end_namespace_decl
118# self._parser.CommentHandler =
119# self._parser.StartCdataSectionHandler =
120# self._parser.EndCdataSectionHandler =
121# self._parser.DefaultHandler =
122# self._parser.DefaultHandlerExpand =
123# self._parser.NotStandaloneHandler =
124 self._parser.ExternalEntityRefHandler = self.external_entity_ref
125
126 # Locator methods
127
128 def getColumnNumber(self):
129 return self._parser.ErrorColumnNumber
130
131 def getLineNumber(self):
132 return self._parser.ErrorLineNumber
133
134 def getPublicId(self):
135 return self._source.getPublicId()
136
137 def getSystemId(self):
138 return self._parser.GetBase()
139
Fred Drake45cd9de2000-06-29 19:34:54 +0000140 # event handlers
Fred Drake45cd9de2000-06-29 19:34:54 +0000141 def start_element(self, name, attrs):
Lars Gustäbel32bf12e2000-09-24 18:39:23 +0000142 self._cont_handler.startElement(name, AttributesImpl(attrs))
Fred Drake45cd9de2000-06-29 19:34:54 +0000143
144 def end_element(self, name):
Lars Gustäbelf43cf312000-09-24 18:29:24 +0000145 self._cont_handler.endElement(name)
Fred Drake45cd9de2000-06-29 19:34:54 +0000146
147 def start_element_ns(self, name, attrs):
Fred Drake96ea1962000-09-23 04:49:30 +0000148 pair = name.split()
Fred Drake45cd9de2000-06-29 19:34:54 +0000149 if len(pair) == 1:
Lars Gustäbelf43cf312000-09-24 18:29:24 +0000150 pair = (None, name)
Fred Drake45cd9de2000-06-29 19:34:54 +0000151
Lars Gustäbel32bf12e2000-09-24 18:39:23 +0000152 newattrs = {}
153 for (aname, value) in attrs.items():
154 apair = aname.split()
155 if len(apair) == 1:
156 apair = (None, aname)
157 else:
158 apair = tuple(apair)
159
160 newattrs[apair] = value
161
162 self._cont_handler.startElementNS(pair, None,
163 AttributesNSImpl(newattrs, {}))
Fred Drake45cd9de2000-06-29 19:34:54 +0000164
165 def end_element_ns(self, name):
Fred Drake96ea1962000-09-23 04:49:30 +0000166 pair = name.split()
Fred Drake45cd9de2000-06-29 19:34:54 +0000167 if len(pair) == 1:
Lars Gustäbel32bf12e2000-09-24 18:39:23 +0000168 pair = (None, name)
Fred Drake45cd9de2000-06-29 19:34:54 +0000169
Lars Gustäbelf43cf312000-09-24 18:29:24 +0000170 self._cont_handler.endElementNS(pair, None)
Fred Drake45cd9de2000-06-29 19:34:54 +0000171
Lars Gustäbelf43cf312000-09-24 18:29:24 +0000172 # this is not used (call directly to ContentHandler)
Fred Drake45cd9de2000-06-29 19:34:54 +0000173 def processing_instruction(self, target, data):
174 self._cont_handler.processingInstruction(target, data)
175
Lars Gustäbelf43cf312000-09-24 18:29:24 +0000176 # this is not used (call directly to ContentHandler)
Fred Drake45cd9de2000-06-29 19:34:54 +0000177 def character_data(self, data):
178 self._cont_handler.characters(data)
179
180 def start_namespace_decl(self, prefix, uri):
181 self._cont_handler.startPrefixMapping(prefix, uri)
182
183 def end_namespace_decl(self, prefix):
184 self._cont_handler.endPrefixMapping(prefix)
185
186 def unparsed_entity_decl(self, name, base, sysid, pubid, notation_name):
187 self._dtd_handler.unparsedEntityDecl(name, pubid, sysid, notation_name)
188
189 def notation_decl(self, name, base, sysid, pubid):
190 self._dtd_handler.notationDecl(name, pubid, sysid)
191
192 def external_entity_ref(self, context, base, sysid, pubid):
Lars Gustäbelf43cf312000-09-24 18:29:24 +0000193 raise NotImplementedError()
Fred Drake45cd9de2000-06-29 19:34:54 +0000194 source = self._ent_handler.resolveEntity(pubid, sysid)
195 source = saxutils.prepare_input_source(source)
196 # FIXME: create new parser, stack self._source and self._parser
197 # FIXME: reuse code from self.parse(...)
198 return 1
199
200# ---
201
202def create_parser(*args, **kwargs):
Fred Drakeddb48672000-09-23 05:32:26 +0000203 return apply(ExpatParser, args, kwargs)
Fred Drake45cd9de2000-06-29 19:34:54 +0000204
205# ---
206
207if __name__ == "__main__":
208 import xml.sax
209 p = create_parser()
210 p.setContentHandler(xml.sax.XMLGenerator())
211 p.setErrorHandler(xml.sax.ErrorHandler())
212 p.parse("../../../hamlet.xml")