xmlreader.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. """An XML Reader is the SAX 2 name for an XML parser. XML Parsers
  2. should be based on this code. """
  3. from . import handler
  4. from ._exceptions import SAXNotSupportedException, SAXNotRecognizedException
  5. # ===== XMLREADER =====
  6. class XMLReader:
  7. """Interface for reading an XML document using callbacks.
  8. XMLReader is the interface that an XML parser's SAX2 driver must
  9. implement. This interface allows an application to set and query
  10. features and properties in the parser, to register event handlers
  11. for document processing, and to initiate a document parse.
  12. All SAX interfaces are assumed to be synchronous: the parse
  13. methods must not return until parsing is complete, and readers
  14. must wait for an event-handler callback to return before reporting
  15. the next event."""
  16. def __init__(self):
  17. self._cont_handler = handler.ContentHandler()
  18. self._dtd_handler = handler.DTDHandler()
  19. self._ent_handler = handler.EntityResolver()
  20. self._err_handler = handler.ErrorHandler()
  21. def parse(self, source):
  22. "Parse an XML document from a system identifier or an InputSource."
  23. raise NotImplementedError("This method must be implemented!")
  24. def getContentHandler(self):
  25. "Returns the current ContentHandler."
  26. return self._cont_handler
  27. def setContentHandler(self, handler):
  28. "Registers a new object to receive document content events."
  29. self._cont_handler = handler
  30. def getDTDHandler(self):
  31. "Returns the current DTD handler."
  32. return self._dtd_handler
  33. def setDTDHandler(self, handler):
  34. "Register an object to receive basic DTD-related events."
  35. self._dtd_handler = handler
  36. def getEntityResolver(self):
  37. "Returns the current EntityResolver."
  38. return self._ent_handler
  39. def setEntityResolver(self, resolver):
  40. "Register an object to resolve external entities."
  41. self._ent_handler = resolver
  42. def getErrorHandler(self):
  43. "Returns the current ErrorHandler."
  44. return self._err_handler
  45. def setErrorHandler(self, handler):
  46. "Register an object to receive error-message events."
  47. self._err_handler = handler
  48. def setLocale(self, locale):
  49. """Allow an application to set the locale for errors and warnings.
  50. SAX parsers are not required to provide localization for errors
  51. and warnings; if they cannot support the requested locale,
  52. however, they must raise a SAX exception. Applications may
  53. request a locale change in the middle of a parse."""
  54. raise SAXNotSupportedException("Locale support not implemented")
  55. def getFeature(self, name):
  56. "Looks up and returns the state of a SAX2 feature."
  57. raise SAXNotRecognizedException("Feature '%s' not recognized" % name)
  58. def setFeature(self, name, state):
  59. "Sets the state of a SAX2 feature."
  60. raise SAXNotRecognizedException("Feature '%s' not recognized" % name)
  61. def getProperty(self, name):
  62. "Looks up and returns the value of a SAX2 property."
  63. raise SAXNotRecognizedException("Property '%s' not recognized" % name)
  64. def setProperty(self, name, value):
  65. "Sets the value of a SAX2 property."
  66. raise SAXNotRecognizedException("Property '%s' not recognized" % name)
  67. class IncrementalParser(XMLReader):
  68. """This interface adds three extra methods to the XMLReader
  69. interface that allow XML parsers to support incremental
  70. parsing. Support for this interface is optional, since not all
  71. underlying XML parsers support this functionality.
  72. When the parser is instantiated it is ready to begin accepting
  73. data from the feed method immediately. After parsing has been
  74. finished with a call to close the reset method must be called to
  75. make the parser ready to accept new data, either from feed or
  76. using the parse method.
  77. Note that these methods must _not_ be called during parsing, that
  78. is, after parse has been called and before it returns.
  79. By default, the class also implements the parse method of the XMLReader
  80. interface using the feed, close and reset methods of the
  81. IncrementalParser interface as a convenience to SAX 2.0 driver
  82. writers."""
  83. def __init__(self, bufsize=2**16):
  84. self._bufsize = bufsize
  85. XMLReader.__init__(self)
  86. def parse(self, source):
  87. from . import saxutils
  88. source = saxutils.prepare_input_source(source)
  89. self.prepareParser(source)
  90. file = source.getCharacterStream()
  91. if file is None:
  92. file = source.getByteStream()
  93. buffer = file.read(self._bufsize)
  94. while buffer:
  95. self.feed(buffer)
  96. buffer = file.read(self._bufsize)
  97. self.close()
  98. def feed(self, data):
  99. """This method gives the raw XML data in the data parameter to
  100. the parser and makes it parse the data, emitting the
  101. corresponding events. It is allowed for XML constructs to be
  102. split across several calls to feed.
  103. feed may raise SAXException."""
  104. raise NotImplementedError("This method must be implemented!")
  105. def prepareParser(self, source):
  106. """This method is called by the parse implementation to allow
  107. the SAX 2.0 driver to prepare itself for parsing."""
  108. raise NotImplementedError("prepareParser must be overridden!")
  109. def close(self):
  110. """This method is called when the entire XML document has been
  111. passed to the parser through the feed method, to notify the
  112. parser that there are no more data. This allows the parser to
  113. do the final checks on the document and empty the internal
  114. data buffer.
  115. The parser will not be ready to parse another document until
  116. the reset method has been called.
  117. close may raise SAXException."""
  118. raise NotImplementedError("This method must be implemented!")
  119. def reset(self):
  120. """This method is called after close has been called to reset
  121. the parser so that it is ready to parse new documents. The
  122. results of calling parse or feed after close without calling
  123. reset are undefined."""
  124. raise NotImplementedError("This method must be implemented!")
  125. # ===== LOCATOR =====
  126. class Locator:
  127. """Interface for associating a SAX event with a document
  128. location. A locator object will return valid results only during
  129. calls to DocumentHandler methods; at any other time, the
  130. results are unpredictable."""
  131. def getColumnNumber(self):
  132. "Return the column number where the current event ends."
  133. return -1
  134. def getLineNumber(self):
  135. "Return the line number where the current event ends."
  136. return -1
  137. def getPublicId(self):
  138. "Return the public identifier for the current event."
  139. return None
  140. def getSystemId(self):
  141. "Return the system identifier for the current event."
  142. return None
  143. # ===== INPUTSOURCE =====
  144. class InputSource:
  145. """Encapsulation of the information needed by the XMLReader to
  146. read entities.
  147. This class may include information about the public identifier,
  148. system identifier, byte stream (possibly with character encoding
  149. information) and/or the character stream of an entity.
  150. Applications will create objects of this class for use in the
  151. XMLReader.parse method and for returning from
  152. EntityResolver.resolveEntity.
  153. An InputSource belongs to the application, the XMLReader is not
  154. allowed to modify InputSource objects passed to it from the
  155. application, although it may make copies and modify those."""
  156. def __init__(self, system_id = None):
  157. self.__system_id = system_id
  158. self.__public_id = None
  159. self.__encoding = None
  160. self.__bytefile = None
  161. self.__charfile = None
  162. def setPublicId(self, public_id):
  163. "Sets the public identifier of this InputSource."
  164. self.__public_id = public_id
  165. def getPublicId(self):
  166. "Returns the public identifier of this InputSource."
  167. return self.__public_id
  168. def setSystemId(self, system_id):
  169. "Sets the system identifier of this InputSource."
  170. self.__system_id = system_id
  171. def getSystemId(self):
  172. "Returns the system identifier of this InputSource."
  173. return self.__system_id
  174. def setEncoding(self, encoding):
  175. """Sets the character encoding of this InputSource.
  176. The encoding must be a string acceptable for an XML encoding
  177. declaration (see section 4.3.3 of the XML recommendation).
  178. The encoding attribute of the InputSource is ignored if the
  179. InputSource also contains a character stream."""
  180. self.__encoding = encoding
  181. def getEncoding(self):
  182. "Get the character encoding of this InputSource."
  183. return self.__encoding
  184. def setByteStream(self, bytefile):
  185. """Set the byte stream (a Python file-like object which does
  186. not perform byte-to-character conversion) for this input
  187. source.
  188. The SAX parser will ignore this if there is also a character
  189. stream specified, but it will use a byte stream in preference
  190. to opening a URI connection itself.
  191. If the application knows the character encoding of the byte
  192. stream, it should set it with the setEncoding method."""
  193. self.__bytefile = bytefile
  194. def getByteStream(self):
  195. """Get the byte stream for this input source.
  196. The getEncoding method will return the character encoding for
  197. this byte stream, or None if unknown."""
  198. return self.__bytefile
  199. def setCharacterStream(self, charfile):
  200. """Set the character stream for this input source. (The stream
  201. must be a Python 2.0 Unicode-wrapped file-like that performs
  202. conversion to Unicode strings.)
  203. If there is a character stream specified, the SAX parser will
  204. ignore any byte stream and will not attempt to open a URI
  205. connection to the system identifier."""
  206. self.__charfile = charfile
  207. def getCharacterStream(self):
  208. "Get the character stream for this input source."
  209. return self.__charfile
  210. # ===== ATTRIBUTESIMPL =====
  211. class AttributesImpl:
  212. def __init__(self, attrs):
  213. """Non-NS-aware implementation.
  214. attrs should be of the form {name : value}."""
  215. self._attrs = attrs
  216. def getLength(self):
  217. return len(self._attrs)
  218. def getType(self, name):
  219. return "CDATA"
  220. def getValue(self, name):
  221. return self._attrs[name]
  222. def getValueByQName(self, name):
  223. return self._attrs[name]
  224. def getNameByQName(self, name):
  225. if name not in self._attrs:
  226. raise KeyError(name)
  227. return name
  228. def getQNameByName(self, name):
  229. if name not in self._attrs:
  230. raise KeyError(name)
  231. return name
  232. def getNames(self):
  233. return list(self._attrs.keys())
  234. def getQNames(self):
  235. return list(self._attrs.keys())
  236. def __len__(self):
  237. return len(self._attrs)
  238. def __getitem__(self, name):
  239. return self._attrs[name]
  240. def keys(self):
  241. return list(self._attrs.keys())
  242. def __contains__(self, name):
  243. return name in self._attrs
  244. def get(self, name, alternative=None):
  245. return self._attrs.get(name, alternative)
  246. def copy(self):
  247. return self.__class__(self._attrs)
  248. def items(self):
  249. return list(self._attrs.items())
  250. def values(self):
  251. return list(self._attrs.values())
  252. # ===== ATTRIBUTESNSIMPL =====
  253. class AttributesNSImpl(AttributesImpl):
  254. def __init__(self, attrs, qnames):
  255. """NS-aware implementation.
  256. attrs should be of the form {(ns_uri, lname): value, ...}.
  257. qnames of the form {(ns_uri, lname): qname, ...}."""
  258. self._attrs = attrs
  259. self._qnames = qnames
  260. def getValueByQName(self, name):
  261. for (nsname, qname) in self._qnames.items():
  262. if qname == name:
  263. return self._attrs[nsname]
  264. raise KeyError(name)
  265. def getNameByQName(self, name):
  266. for (nsname, qname) in self._qnames.items():
  267. if qname == name:
  268. return nsname
  269. raise KeyError(name)
  270. def getQNameByName(self, name):
  271. return self._qnames[name]
  272. def getQNames(self):
  273. return list(self._qnames.values())
  274. def copy(self):
  275. return self.__class__(self._attrs, self._qnames)
  276. def _test():
  277. XMLReader()
  278. IncrementalParser()
  279. Locator()
  280. if __name__ == "__main__":
  281. _test()