xmlreader.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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. while buffer := file.read(self._bufsize):
  94. self.feed(buffer)
  95. self.close()
  96. def feed(self, data):
  97. """This method gives the raw XML data in the data parameter to
  98. the parser and makes it parse the data, emitting the
  99. corresponding events. It is allowed for XML constructs to be
  100. split across several calls to feed.
  101. feed may raise SAXException."""
  102. raise NotImplementedError("This method must be implemented!")
  103. def prepareParser(self, source):
  104. """This method is called by the parse implementation to allow
  105. the SAX 2.0 driver to prepare itself for parsing."""
  106. raise NotImplementedError("prepareParser must be overridden!")
  107. def close(self):
  108. """This method is called when the entire XML document has been
  109. passed to the parser through the feed method, to notify the
  110. parser that there are no more data. This allows the parser to
  111. do the final checks on the document and empty the internal
  112. data buffer.
  113. The parser will not be ready to parse another document until
  114. the reset method has been called.
  115. close may raise SAXException."""
  116. raise NotImplementedError("This method must be implemented!")
  117. def reset(self):
  118. """This method is called after close has been called to reset
  119. the parser so that it is ready to parse new documents. The
  120. results of calling parse or feed after close without calling
  121. reset are undefined."""
  122. raise NotImplementedError("This method must be implemented!")
  123. # ===== LOCATOR =====
  124. class Locator:
  125. """Interface for associating a SAX event with a document
  126. location. A locator object will return valid results only during
  127. calls to DocumentHandler methods; at any other time, the
  128. results are unpredictable."""
  129. def getColumnNumber(self):
  130. "Return the column number where the current event ends."
  131. return -1
  132. def getLineNumber(self):
  133. "Return the line number where the current event ends."
  134. return -1
  135. def getPublicId(self):
  136. "Return the public identifier for the current event."
  137. return None
  138. def getSystemId(self):
  139. "Return the system identifier for the current event."
  140. return None
  141. # ===== INPUTSOURCE =====
  142. class InputSource:
  143. """Encapsulation of the information needed by the XMLReader to
  144. read entities.
  145. This class may include information about the public identifier,
  146. system identifier, byte stream (possibly with character encoding
  147. information) and/or the character stream of an entity.
  148. Applications will create objects of this class for use in the
  149. XMLReader.parse method and for returning from
  150. EntityResolver.resolveEntity.
  151. An InputSource belongs to the application, the XMLReader is not
  152. allowed to modify InputSource objects passed to it from the
  153. application, although it may make copies and modify those."""
  154. def __init__(self, system_id = None):
  155. self.__system_id = system_id
  156. self.__public_id = None
  157. self.__encoding = None
  158. self.__bytefile = None
  159. self.__charfile = None
  160. def setPublicId(self, public_id):
  161. "Sets the public identifier of this InputSource."
  162. self.__public_id = public_id
  163. def getPublicId(self):
  164. "Returns the public identifier of this InputSource."
  165. return self.__public_id
  166. def setSystemId(self, system_id):
  167. "Sets the system identifier of this InputSource."
  168. self.__system_id = system_id
  169. def getSystemId(self):
  170. "Returns the system identifier of this InputSource."
  171. return self.__system_id
  172. def setEncoding(self, encoding):
  173. """Sets the character encoding of this InputSource.
  174. The encoding must be a string acceptable for an XML encoding
  175. declaration (see section 4.3.3 of the XML recommendation).
  176. The encoding attribute of the InputSource is ignored if the
  177. InputSource also contains a character stream."""
  178. self.__encoding = encoding
  179. def getEncoding(self):
  180. "Get the character encoding of this InputSource."
  181. return self.__encoding
  182. def setByteStream(self, bytefile):
  183. """Set the byte stream (a Python file-like object which does
  184. not perform byte-to-character conversion) for this input
  185. source.
  186. The SAX parser will ignore this if there is also a character
  187. stream specified, but it will use a byte stream in preference
  188. to opening a URI connection itself.
  189. If the application knows the character encoding of the byte
  190. stream, it should set it with the setEncoding method."""
  191. self.__bytefile = bytefile
  192. def getByteStream(self):
  193. """Get the byte stream for this input source.
  194. The getEncoding method will return the character encoding for
  195. this byte stream, or None if unknown."""
  196. return self.__bytefile
  197. def setCharacterStream(self, charfile):
  198. """Set the character stream for this input source. (The stream
  199. must be a Python 2.0 Unicode-wrapped file-like that performs
  200. conversion to Unicode strings.)
  201. If there is a character stream specified, the SAX parser will
  202. ignore any byte stream and will not attempt to open a URI
  203. connection to the system identifier."""
  204. self.__charfile = charfile
  205. def getCharacterStream(self):
  206. "Get the character stream for this input source."
  207. return self.__charfile
  208. # ===== ATTRIBUTESIMPL =====
  209. class AttributesImpl:
  210. def __init__(self, attrs):
  211. """Non-NS-aware implementation.
  212. attrs should be of the form {name : value}."""
  213. self._attrs = attrs
  214. def getLength(self):
  215. return len(self._attrs)
  216. def getType(self, name):
  217. return "CDATA"
  218. def getValue(self, name):
  219. return self._attrs[name]
  220. def getValueByQName(self, name):
  221. return self._attrs[name]
  222. def getNameByQName(self, name):
  223. if name not in self._attrs:
  224. raise KeyError(name)
  225. return name
  226. def getQNameByName(self, name):
  227. if name not in self._attrs:
  228. raise KeyError(name)
  229. return name
  230. def getNames(self):
  231. return list(self._attrs.keys())
  232. def getQNames(self):
  233. return list(self._attrs.keys())
  234. def __len__(self):
  235. return len(self._attrs)
  236. def __getitem__(self, name):
  237. return self._attrs[name]
  238. def keys(self):
  239. return list(self._attrs.keys())
  240. def __contains__(self, name):
  241. return name in self._attrs
  242. def get(self, name, alternative=None):
  243. return self._attrs.get(name, alternative)
  244. def copy(self):
  245. return self.__class__(self._attrs)
  246. def items(self):
  247. return list(self._attrs.items())
  248. def values(self):
  249. return list(self._attrs.values())
  250. # ===== ATTRIBUTESNSIMPL =====
  251. class AttributesNSImpl(AttributesImpl):
  252. def __init__(self, attrs, qnames):
  253. """NS-aware implementation.
  254. attrs should be of the form {(ns_uri, lname): value, ...}.
  255. qnames of the form {(ns_uri, lname): qname, ...}."""
  256. self._attrs = attrs
  257. self._qnames = qnames
  258. def getValueByQName(self, name):
  259. for (nsname, qname) in self._qnames.items():
  260. if qname == name:
  261. return self._attrs[nsname]
  262. raise KeyError(name)
  263. def getNameByQName(self, name):
  264. for (nsname, qname) in self._qnames.items():
  265. if qname == name:
  266. return nsname
  267. raise KeyError(name)
  268. def getQNameByName(self, name):
  269. return self._qnames[name]
  270. def getQNames(self):
  271. return list(self._qnames.values())
  272. def copy(self):
  273. return self.__class__(self._attrs, self._qnames)
  274. def _test():
  275. XMLReader()
  276. IncrementalParser()
  277. Locator()
  278. if __name__ == "__main__":
  279. _test()