blob: e541824ead6bb8a89e68a1c6c2f2864a314df656 [file] [log] [blame]
Fred Drake45cd9de2000-06-29 19:34:54 +00001"""
2SAX driver for the Pyexpat C module. This driver works with
Lars Gustäbelbb757132000-09-24 20:38:18 +00003pyexpat.__version__ == '2.22'.
Fred Drake45cd9de2000-06-29 19:34:54 +00004"""
5
Fred Drake45cd9de2000-06-29 19:34:54 +00006version = "0.20"
7
Lars Gustäbelf43cf312000-09-24 18:29:24 +00008from xml.sax._exceptions import *
Martin v. Löwisfb73bb12001-06-17 07:05:43 +00009
10# xml.parsers.expat does not raise ImportError in Jython
11import sys
Fred Drakec974bf42001-07-30 22:41:23 +000012if sys.platform[:4] == "java":
Martin v. Löwisfb73bb12001-06-17 07:05:43 +000013 raise SAXReaderNotAvailable("expat not available in Java", None)
14del sys
15
Martin v. Löwis962c9e72000-10-06 17:41:52 +000016try:
17 from xml.parsers import expat
18except ImportError:
Fred Drakec974bf42001-07-30 22:41:23 +000019 raise SAXReaderNotAvailable("expat not supported", None)
Jeremy Hyltone3c37d62001-07-30 21:49:22 +000020else:
21 if not hasattr(expat, "ParserCreate"):
Fred Drakec974bf42001-07-30 22:41:23 +000022 raise SAXReaderNotAvailable("expat not supported", None)
Martin v. Löwis2066fa02000-09-24 21:17:39 +000023from xml.sax import xmlreader, saxutils, handler
Fred Drake45cd9de2000-06-29 19:34:54 +000024
Lars Gustäbel32bf12e2000-09-24 18:39:23 +000025AttributesImpl = xmlreader.AttributesImpl
26AttributesNSImpl = xmlreader.AttributesNSImpl
27
Fred Drake012c81f2002-04-04 17:57:08 +000028import weakref
29
30# --- ExpatLocator
31
32class ExpatLocator(xmlreader.Locator):
33 """Locator for use with the ExpatParser class.
34
35 This uses a weak reference to the parser object to avoid creating
36 a circular reference between the parser and the content handler.
37 """
38 def __init__(self, parser):
39 self._ref = weakref.ref(parser)
40
41 def getColumnNumber(self):
42 parser = self._ref()
43 if parser is None or parser._parser is None:
44 return None
45 return parser._parser.ErrorColumnNumber
46
47 def getLineNumber(self):
48 parser = self._ref()
49 if parser is None or parser._parser is None:
50 return 1
Fred Drakeda204da2002-04-04 19:12:31 +000051 return parser._parser.ErrorLineNumber
Fred Drake012c81f2002-04-04 17:57:08 +000052
53 def getPublicId(self):
54 parser = self._ref()
55 if parser is None:
56 return None
57 return parser._source.getPublicId()
58
59 def getSystemId(self):
60 parser = self._ref()
61 if parser is None:
62 return None
63 return parser._source.getSystemId()
64
Martin v. Löwis3f0969f2000-09-29 19:00:40 +000065
Fred Drake45cd9de2000-06-29 19:34:54 +000066# --- ExpatParser
67
Fred Drakeddb48672000-09-23 05:32:26 +000068class ExpatParser(xmlreader.IncrementalParser, xmlreader.Locator):
Fred Drake45cd9de2000-06-29 19:34:54 +000069 "SAX driver for the Pyexpat C module."
70
71 def __init__(self, namespaceHandling=0, bufsize=2**16-20):
72 xmlreader.IncrementalParser.__init__(self, bufsize)
Lars Gustäbele292a242000-09-24 20:19:45 +000073 self._source = xmlreader.InputSource()
Fred Drake45cd9de2000-06-29 19:34:54 +000074 self._parser = None
75 self._namespaces = namespaceHandling
Martin v. Löwis05917252001-01-27 08:56:24 +000076 self._lex_handler_prop = None
Fred Drake45cd9de2000-06-29 19:34:54 +000077 self._parsing = 0
Lars Gustäbele292a242000-09-24 20:19:45 +000078 self._entity_stack = []
Fred Drake45cd9de2000-06-29 19:34:54 +000079
80 # XMLReader methods
81
Lars Gustäbel523b0a62000-09-24 18:54:49 +000082 def parse(self, source):
Lars Gustäbelbb757132000-09-24 20:38:18 +000083 "Parse an XML document from a URL or an InputSource."
Lars Gustäbel523b0a62000-09-24 18:54:49 +000084 source = saxutils.prepare_input_source(source)
85
86 self._source = source
Fred Drake45cd9de2000-06-29 19:34:54 +000087 self.reset()
Fred Drake012c81f2002-04-04 17:57:08 +000088 self._cont_handler.setDocumentLocator(ExpatLocator(self))
Fred Drake16f63292000-10-23 18:09:50 +000089 xmlreader.IncrementalParser.parse(self, source)
Fred Drake45cd9de2000-06-29 19:34:54 +000090
Lars Gustäbel523b0a62000-09-24 18:54:49 +000091 def prepareParser(self, source):
92 if source.getSystemId() != None:
93 self._parser.SetBase(source.getSystemId())
Fred Drake16f63292000-10-23 18:09:50 +000094
Martin v. Löwisfb73bb12001-06-17 07:05:43 +000095 # Redefined setContentHandle to allow changing handlers during parsing
96
97 def setContentHandler(self, handler):
98 xmlreader.IncrementalParser.setContentHandler(self, handler)
99 if self._parsing:
100 self._reset_cont_handler()
101
Fred Drake45cd9de2000-06-29 19:34:54 +0000102 def getFeature(self, name):
Martin v. Löwis2066fa02000-09-24 21:17:39 +0000103 if name == handler.feature_namespaces:
Lars Gustäbelf43cf312000-09-24 18:29:24 +0000104 return self._namespaces
Fred Drake45cd9de2000-06-29 19:34:54 +0000105 raise SAXNotRecognizedException("Feature '%s' not recognized" % name)
106
107 def setFeature(self, name, state):
Lars Gustäbelf43cf312000-09-24 18:29:24 +0000108 if self._parsing:
109 raise SAXNotSupportedException("Cannot set features while parsing")
Martin v. Löwis2066fa02000-09-24 21:17:39 +0000110 if name == handler.feature_namespaces:
Lars Gustäbelf43cf312000-09-24 18:29:24 +0000111 self._namespaces = state
112 else:
113 raise SAXNotRecognizedException("Feature '%s' not recognized" %
114 name)
Fred Drake45cd9de2000-06-29 19:34:54 +0000115
116 def getProperty(self, name):
Martin v. Löwis05917252001-01-27 08:56:24 +0000117 if name == handler.property_lexical_handler:
118 return self._lex_handler_prop
Fred Drake45cd9de2000-06-29 19:34:54 +0000119 raise SAXNotRecognizedException("Property '%s' not recognized" % name)
120
121 def setProperty(self, name, value):
Martin v. Löwis05917252001-01-27 08:56:24 +0000122 if name == handler.property_lexical_handler:
123 self._lex_handler_prop = value
Martin v. Löwisfb73bb12001-06-17 07:05:43 +0000124 if self._parsing:
125 self._reset_lex_handler_prop()
Martin v. Löwis05917252001-01-27 08:56:24 +0000126 else:
127 raise SAXNotRecognizedException("Property '%s' not recognized" % name)
Fred Drake45cd9de2000-06-29 19:34:54 +0000128
129 # IncrementalParser methods
130
Martin v. Löwisee1dc152000-10-06 21:08:59 +0000131 def feed(self, data, isFinal = 0):
Fred Drake45cd9de2000-06-29 19:34:54 +0000132 if not self._parsing:
Fred Drake45cd9de2000-06-29 19:34:54 +0000133 self.reset()
Lars Gustäbel55b4efd2000-10-14 10:28:01 +0000134 self._parsing = 1
Fred Drake45cd9de2000-06-29 19:34:54 +0000135 self._cont_handler.startDocument()
Lars Gustäbelf43cf312000-09-24 18:29:24 +0000136
Martin v. Löwisee1dc152000-10-06 21:08:59 +0000137 try:
138 # The isFinal parameter is internal to the expat reader.
139 # If it is set to true, expat will check validity of the entire
140 # document. When feeding chunks, they are not normally final -
141 # except when invoked from close.
142 self._parser.Parse(data, isFinal)
143 except expat.error:
144 error_code = self._parser.ErrorCode
Martin v. Löwis04f49432000-10-09 16:45:54 +0000145 exc = SAXParseException(expat.ErrorString(error_code), None, self)
Martin v. Löwis05917252001-01-27 08:56:24 +0000146 # FIXME: when to invoke error()?
Martin v. Löwis04f49432000-10-09 16:45:54 +0000147 self._err_handler.fatalError(exc)
Fred Drake45cd9de2000-06-29 19:34:54 +0000148
149 def close(self):
Martin v. Löwisee1dc152000-10-06 21:08:59 +0000150 if self._entity_stack:
151 # If we are completing an external entity, do nothing here
152 return
153 self.feed("", isFinal = 1)
154 self._cont_handler.endDocument()
155 self._parsing = 0
Martin v. Löwis05917252001-01-27 08:56:24 +0000156 # break cycle created by expat handlers pointing to our methods
157 self._parser = None
Fred Drake16f63292000-10-23 18:09:50 +0000158
Martin v. Löwisfb73bb12001-06-17 07:05:43 +0000159 def _reset_cont_handler(self):
160 self._parser.ProcessingInstructionHandler = \
161 self._cont_handler.processingInstruction
162 self._parser.CharacterDataHandler = self._cont_handler.characters
163
164 def _reset_lex_handler_prop(self):
165 self._parser.CommentHandler = self._lex_handler_prop.comment
166 self._parser.StartCdataSectionHandler = self._lex_handler_prop.startCDATA
167 self._parser.EndCdataSectionHandler = self._lex_handler_prop.endCDATA
168
Fred Drake45cd9de2000-06-29 19:34:54 +0000169 def reset(self):
170 if self._namespaces:
Fred Drake96ea1962000-09-23 04:49:30 +0000171 self._parser = expat.ParserCreate(None, " ")
Fred Drake45cd9de2000-06-29 19:34:54 +0000172 self._parser.StartElementHandler = self.start_element_ns
173 self._parser.EndElementHandler = self.end_element_ns
174 else:
Fred Drake96ea1962000-09-23 04:49:30 +0000175 self._parser = expat.ParserCreate()
Paul Prescod6c4753f2000-07-04 03:39:33 +0000176 self._parser.StartElementHandler = self.start_element
177 self._parser.EndElementHandler = self.end_element
Fred Drake45cd9de2000-06-29 19:34:54 +0000178
Martin v. Löwisfb73bb12001-06-17 07:05:43 +0000179 self._reset_cont_handler()
Fred Drake45cd9de2000-06-29 19:34:54 +0000180 self._parser.UnparsedEntityDeclHandler = self.unparsed_entity_decl
181 self._parser.NotationDeclHandler = self.notation_decl
182 self._parser.StartNamespaceDeclHandler = self.start_namespace_decl
183 self._parser.EndNamespaceDeclHandler = self.end_namespace_decl
Martin v. Löwis70d39a62001-01-27 09:01:20 +0000184
Martin v. Löwis05917252001-01-27 08:56:24 +0000185 self._decl_handler_prop = None
186 if self._lex_handler_prop:
Martin v. Löwisfb73bb12001-06-17 07:05:43 +0000187 self._reset_lex_handler_prop()
Martin v. Löwis70d39a62001-01-27 09:01:20 +0000188# self._parser.DefaultHandler =
189# self._parser.DefaultHandlerExpand =
190# self._parser.NotStandaloneHandler =
Fred Drake45cd9de2000-06-29 19:34:54 +0000191 self._parser.ExternalEntityRefHandler = self.external_entity_ref
Lars Gustäbelbb757132000-09-24 20:38:18 +0000192
Lars Gustäbel55b4efd2000-10-14 10:28:01 +0000193 self._parsing = 0
Lars Gustäbelbb757132000-09-24 20:38:18 +0000194 self._entity_stack = []
Fred Drake16f63292000-10-23 18:09:50 +0000195
Fred Drake45cd9de2000-06-29 19:34:54 +0000196 # Locator methods
197
198 def getColumnNumber(self):
Martin v. Löwis05917252001-01-27 08:56:24 +0000199 if self._parser is None:
200 return None
Fred Drake45cd9de2000-06-29 19:34:54 +0000201 return self._parser.ErrorColumnNumber
202
203 def getLineNumber(self):
Martin v. Löwis05917252001-01-27 08:56:24 +0000204 if self._parser is None:
205 return 1
Fred Drake45cd9de2000-06-29 19:34:54 +0000206 return self._parser.ErrorLineNumber
207
208 def getPublicId(self):
209 return self._source.getPublicId()
210
211 def getSystemId(self):
Martin v. Löwisee1dc152000-10-06 21:08:59 +0000212 return self._source.getSystemId()
Fred Drake16f63292000-10-23 18:09:50 +0000213
Fred Drake45cd9de2000-06-29 19:34:54 +0000214 # event handlers
Fred Drake45cd9de2000-06-29 19:34:54 +0000215 def start_element(self, name, attrs):
Lars Gustäbel32bf12e2000-09-24 18:39:23 +0000216 self._cont_handler.startElement(name, AttributesImpl(attrs))
Fred Drake45cd9de2000-06-29 19:34:54 +0000217
218 def end_element(self, name):
Lars Gustäbelf43cf312000-09-24 18:29:24 +0000219 self._cont_handler.endElement(name)
Fred Drake45cd9de2000-06-29 19:34:54 +0000220
221 def start_element_ns(self, name, attrs):
Neal Norwitzab199622002-05-31 20:46:39 +0000222 pair = name.split()
Fred Drake45cd9de2000-06-29 19:34:54 +0000223 if len(pair) == 1:
Lars Gustäbelf43cf312000-09-24 18:29:24 +0000224 pair = (None, name)
Lars Gustäbeld2f5a9a2000-10-19 07:36:29 +0000225 else:
226 pair = tuple(pair)
Fred Drake45cd9de2000-06-29 19:34:54 +0000227
Lars Gustäbel32bf12e2000-09-24 18:39:23 +0000228 newattrs = {}
229 for (aname, value) in attrs.items():
Neal Norwitzab199622002-05-31 20:46:39 +0000230 apair = aname.split()
Lars Gustäbel32bf12e2000-09-24 18:39:23 +0000231 if len(apair) == 1:
232 apair = (None, aname)
233 else:
234 apair = tuple(apair)
235
236 newattrs[apair] = value
237
Fred Drake16f63292000-10-23 18:09:50 +0000238 self._cont_handler.startElementNS(pair, None,
Lars Gustäbel32bf12e2000-09-24 18:39:23 +0000239 AttributesNSImpl(newattrs, {}))
Fred Drake45cd9de2000-06-29 19:34:54 +0000240
241 def end_element_ns(self, name):
Neal Norwitzab199622002-05-31 20:46:39 +0000242 pair = name.split()
Fred Drake45cd9de2000-06-29 19:34:54 +0000243 if len(pair) == 1:
Lars Gustäbel32bf12e2000-09-24 18:39:23 +0000244 pair = (None, name)
Martin v. Löwis05917252001-01-27 08:56:24 +0000245 else:
246 pair = tuple(pair)
Fred Drake16f63292000-10-23 18:09:50 +0000247
Lars Gustäbelf43cf312000-09-24 18:29:24 +0000248 self._cont_handler.endElementNS(pair, None)
Fred Drake45cd9de2000-06-29 19:34:54 +0000249
Lars Gustäbelf43cf312000-09-24 18:29:24 +0000250 # this is not used (call directly to ContentHandler)
Fred Drake45cd9de2000-06-29 19:34:54 +0000251 def processing_instruction(self, target, data):
252 self._cont_handler.processingInstruction(target, data)
253
Lars Gustäbelf43cf312000-09-24 18:29:24 +0000254 # this is not used (call directly to ContentHandler)
Fred Drake45cd9de2000-06-29 19:34:54 +0000255 def character_data(self, data):
256 self._cont_handler.characters(data)
257
258 def start_namespace_decl(self, prefix, uri):
259 self._cont_handler.startPrefixMapping(prefix, uri)
260
261 def end_namespace_decl(self, prefix):
262 self._cont_handler.endPrefixMapping(prefix)
Fred Drake16f63292000-10-23 18:09:50 +0000263
Fred Drake45cd9de2000-06-29 19:34:54 +0000264 def unparsed_entity_decl(self, name, base, sysid, pubid, notation_name):
265 self._dtd_handler.unparsedEntityDecl(name, pubid, sysid, notation_name)
266
267 def notation_decl(self, name, base, sysid, pubid):
268 self._dtd_handler.notationDecl(name, pubid, sysid)
269
270 def external_entity_ref(self, context, base, sysid, pubid):
Fred Drake45cd9de2000-06-29 19:34:54 +0000271 source = self._ent_handler.resolveEntity(pubid, sysid)
Lars Gustäbele292a242000-09-24 20:19:45 +0000272 source = saxutils.prepare_input_source(source,
273 self._source.getSystemId() or
274 "")
Fred Drake16f63292000-10-23 18:09:50 +0000275
Lars Gustäbele292a242000-09-24 20:19:45 +0000276 self._entity_stack.append((self._parser, self._source))
277 self._parser = self._parser.ExternalEntityParserCreate(context)
278 self._source = source
279
280 try:
281 xmlreader.IncrementalParser.parse(self, source)
Lars Gustäbele292a242000-09-24 20:19:45 +0000282 except:
283 return 0 # FIXME: save error info here?
284
285 (self._parser, self._source) = self._entity_stack[-1]
286 del self._entity_stack[-1]
Fred Drake45cd9de2000-06-29 19:34:54 +0000287 return 1
Fred Drake16f63292000-10-23 18:09:50 +0000288
Fred Drake45cd9de2000-06-29 19:34:54 +0000289# ---
Fred Drake16f63292000-10-23 18:09:50 +0000290
Fred Drake45cd9de2000-06-29 19:34:54 +0000291def create_parser(*args, **kwargs):
Fred Drakeddb48672000-09-23 05:32:26 +0000292 return apply(ExpatParser, args, kwargs)
Fred Drake16f63292000-10-23 18:09:50 +0000293
Fred Drake45cd9de2000-06-29 19:34:54 +0000294# ---
295
296if __name__ == "__main__":
297 import xml.sax
298 p = create_parser()
299 p.setContentHandler(xml.sax.XMLGenerator())
300 p.setErrorHandler(xml.sax.ErrorHandler())
301 p.parse("../../../hamlet.xml")