Kaydet (Commit) 16f6329e authored tarafından Fred Drake's avatar Fred Drake

Make reindent.py happy (lots of trailing whitespace removed).

üst 098b55ab
...@@ -8,7 +8,7 @@ dom -- The W3C Document Object Model. This supports DOM Level 1 + ...@@ -8,7 +8,7 @@ dom -- The W3C Document Object Model. This supports DOM Level 1 +
parsers -- Python wrappers for XML parsers (currently only supports Expat). parsers -- Python wrappers for XML parsers (currently only supports Expat).
sax -- The Simple API for XML, developed by XML-Dev, led by David sax -- The Simple API for XML, developed by XML-Dev, led by David
Megginson and ported to Python by Lars Marius Garshol. This Megginson and ported to Python by Lars Marius Garshol. This
supports the SAX 2 API. supports the SAX 2 API.
""" """
......
...@@ -40,7 +40,7 @@ class Node: ...@@ -40,7 +40,7 @@ class Node:
def __init__(self): def __init__(self):
self.childNodes = [] self.childNodes = []
if Node._debug: if Node._debug:
index = repr(id(self)) + repr(self.__class__) index = repr(id(self)) + repr(self.__class__)
Node.allnodes[index] = repr(self.__dict__) Node.allnodes[index] = repr(self.__dict__)
if Node.debug is None: if Node.debug is None:
...@@ -52,16 +52,16 @@ class Node: ...@@ -52,16 +52,16 @@ class Node:
if key[0:2] == "__": if key[0:2] == "__":
raise AttributeError raise AttributeError
# getattr should never call getattr! # getattr should never call getattr!
if self.__dict__.has_key("inGetAttr"): if self.__dict__.has_key("inGetAttr"):
del self.inGetAttr del self.inGetAttr
raise AttributeError, key raise AttributeError, key
prefix, attrname = key[:5], key[5:] prefix, attrname = key[:5], key[5:]
if prefix == "_get_": if prefix == "_get_":
self.inGetAttr = 1 self.inGetAttr = 1
if hasattr(self, attrname): if hasattr(self, attrname):
del self.inGetAttr del self.inGetAttr
return (lambda self=self, attrname=attrname: return (lambda self=self, attrname=attrname:
getattr(self, attrname)) getattr(self, attrname))
else: else:
del self.inGetAttr del self.inGetAttr
...@@ -213,7 +213,7 @@ class AttributeList: ...@@ -213,7 +213,7 @@ class AttributeList:
def itemsNS(self): def itemsNS(self):
return map(lambda node: ((node.URI, node.localName), node.value), return map(lambda node: ((node.URI, node.localName), node.value),
self._attrs.values()) self._attrs.values())
def keys(self): def keys(self):
return self._attrs.keys() return self._attrs.keys()
...@@ -229,7 +229,7 @@ class AttributeList: ...@@ -229,7 +229,7 @@ class AttributeList:
def __cmp__(self, other): def __cmp__(self, other):
if self._attrs is getattr(other, "_attrs", None): if self._attrs is getattr(other, "_attrs", None):
return 0 return 0
else: else:
return cmp(id(self), id(other)) return cmp(id(self), id(other))
#FIXME: is it appropriate to return .value? #FIXME: is it appropriate to return .value?
...@@ -324,7 +324,7 @@ class Element(Node): ...@@ -324,7 +324,7 @@ class Element(Node):
node.unlink() node.unlink()
del self._attrs[node.name] del self._attrs[node.name]
del self._attrsNS[(node.namespaceURI, node.localName)] del self._attrsNS[(node.namespaceURI, node.localName)]
def getElementsByTagName(self, name): def getElementsByTagName(self, name):
return _getElementsByTagNameHelper(self, name, []) return _getElementsByTagNameHelper(self, name, [])
...@@ -337,7 +337,7 @@ class Element(Node): ...@@ -337,7 +337,7 @@ class Element(Node):
# undocumented # undocumented
def writexml(self, writer): def writexml(self, writer):
writer.write("<" + self.tagName) writer.write("<" + self.tagName)
a_names = self._get_attributes().keys() a_names = self._get_attributes().keys()
a_names.sort() a_names.sort()
...@@ -473,4 +473,3 @@ def parse(*args, **kwargs): ...@@ -473,4 +473,3 @@ def parse(*args, **kwargs):
def parseString(*args, **kwargs): def parseString(*args, **kwargs):
"Parse a file into a DOM from a string" "Parse a file into a DOM from a string"
return _doparse(pulldom.parseString, args, kwargs) return _doparse(pulldom.parseString, args, kwargs)
...@@ -49,7 +49,7 @@ class PullDOM(xml.sax.ContentHandler): ...@@ -49,7 +49,7 @@ class PullDOM(xml.sax.ContentHandler):
attr = self.document.createAttribute(a_localname) attr = self.document.createAttribute(a_localname)
attr.value = value attr.value = value
node.setAttributeNode(attr) node.setAttributeNode(attr)
parent = self.curNode parent = self.curNode
node.parentNode = parent node.parentNode = parent
self.curNode = node self.curNode = node
...@@ -72,7 +72,7 @@ class PullDOM(xml.sax.ContentHandler): ...@@ -72,7 +72,7 @@ class PullDOM(xml.sax.ContentHandler):
attr = self.document.createAttribute(aname) attr = self.document.createAttribute(aname)
attr.value = value attr.value = value
node.setAttributeNode(attr) node.setAttributeNode(attr)
parent = self.curNode parent = self.curNode
node.parentNode = parent node.parentNode = parent
self.curNode = node self.curNode = node
...@@ -87,7 +87,7 @@ class PullDOM(xml.sax.ContentHandler): ...@@ -87,7 +87,7 @@ class PullDOM(xml.sax.ContentHandler):
self.lastEvent = self.lastEvent[1] self.lastEvent = self.lastEvent[1]
#self.events.append((END_ELEMENT, node)) #self.events.append((END_ELEMENT, node))
self.curNode = node.parentNode self.curNode = node.parentNode
def comment(self, s): def comment(self, s):
node = self.document.createComment(s) node = self.document.createComment(s)
parent = self.curNode parent = self.curNode
...@@ -98,7 +98,7 @@ class PullDOM(xml.sax.ContentHandler): ...@@ -98,7 +98,7 @@ class PullDOM(xml.sax.ContentHandler):
def processingInstruction(self, target, data): def processingInstruction(self, target, data):
node = self.document.createProcessingInstruction(target, data) node = self.document.createProcessingInstruction(target, data)
parent = self.curNode parent = self.curNode
node.parentNode = parent node.parentNode = parent
self.lastEvent[1] = [(PROCESSING_INSTRUCTION, node), None] self.lastEvent[1] = [(PROCESSING_INSTRUCTION, node), None]
...@@ -142,9 +142,9 @@ class ErrorHandler: ...@@ -142,9 +142,9 @@ class ErrorHandler:
def warning(self, exception): def warning(self, exception):
print exception print exception
def error(self, exception): def error(self, exception):
raise exception raise exception
def fatalError(self, exception): def fatalError(self, exception):
raise exception raise exception
class DOMEventStream: class DOMEventStream:
def __init__(self, stream, parser, bufsize): def __init__(self, stream, parser, bufsize):
...@@ -202,18 +202,18 @@ class SAX2DOM(PullDOM): ...@@ -202,18 +202,18 @@ class SAX2DOM(PullDOM):
def processingInstruction(self, target, data): def processingInstruction(self, target, data):
PullDOM.processingInstruction(self, target, data) PullDOM.processingInstruction(self, target, data)
node = self.lastEvent[0][1] node = self.lastEvent[0][1]
node.parentNode.appendChild(node) node.parentNode.appendChild(node)
def ignorableWhitespace(self, chars): def ignorableWhitespace(self, chars):
PullDOM.ignorableWhitespace(self, chars) PullDOM.ignorableWhitespace(self, chars)
node = self.lastEvent[0][1] node = self.lastEvent[0][1]
node.parentNode.appendChild(node) node.parentNode.appendChild(node)
def characters(self, chars): def characters(self, chars):
PullDOM.characters(self, chars) PullDOM.characters(self, chars)
node = self.lastEvent[0][1] node = self.lastEvent[0][1]
node.parentNode.appendChild(node) node.parentNode.appendChild(node)
default_bufsize = (2 ** 14) - 20 default_bufsize = (2 ** 14) - 20
def parse(stream_or_string, parser=None, bufsize=default_bufsize): def parse(stream_or_string, parser=None, bufsize=default_bufsize):
...@@ -221,7 +221,7 @@ def parse(stream_or_string, parser=None, bufsize=default_bufsize): ...@@ -221,7 +221,7 @@ def parse(stream_or_string, parser=None, bufsize=default_bufsize):
stream = open(stream_or_string) stream = open(stream_or_string)
else: else:
stream = stream_or_string stream = stream_or_string
if not parser: if not parser:
parser = xml.sax.make_parser() parser = xml.sax.make_parser()
return DOMEventStream(stream, parser, bufsize) return DOMEventStream(stream, parser, bufsize)
...@@ -230,7 +230,7 @@ def parseString(string, parser=None): ...@@ -230,7 +230,7 @@ def parseString(string, parser=None):
from cStringIO import StringIO from cStringIO import StringIO
except ImportError: except ImportError:
from StringIO import StringIO from StringIO import StringIO
bufsize = len(string) bufsize = len(string)
buf = StringIO(string) buf = StringIO(string)
if not parser: if not parser:
......
...@@ -37,7 +37,7 @@ def parseString(string, handler, errorHandler=ErrorHandler()): ...@@ -37,7 +37,7 @@ def parseString(string, handler, errorHandler=ErrorHandler()):
from cStringIO import StringIO from cStringIO import StringIO
except ImportError: except ImportError:
from StringIO import StringIO from StringIO import StringIO
if errorHandler is None: if errorHandler is None:
errorHandler = ErrorHandler() errorHandler = ErrorHandler()
parser = make_parser() parser = make_parser()
...@@ -61,8 +61,8 @@ del os ...@@ -61,8 +61,8 @@ del os
_key = "python.xml.sax.parser" _key = "python.xml.sax.parser"
if sys.platform[:4] == "java" and sys.registry.containsKey(_key): if sys.platform[:4] == "java" and sys.registry.containsKey(_key):
default_parser_list = string.split(sys.registry.getProperty(_key), ",") default_parser_list = string.split(sys.registry.getProperty(_key), ",")
def make_parser(parser_list = []): def make_parser(parser_list = []):
"""Creates and returns a SAX parser. """Creates and returns a SAX parser.
...@@ -85,8 +85,8 @@ def make_parser(parser_list = []): ...@@ -85,8 +85,8 @@ def make_parser(parser_list = []):
# so try the next one # so try the next one
pass pass
raise SAXReaderNotAvailable("No parsers found", None) raise SAXReaderNotAvailable("No parsers found", None)
# --- Internal utility methods used by make_parser # --- Internal utility methods used by make_parser
if sys.platform[ : 4] == "java": if sys.platform[ : 4] == "java":
......
...@@ -42,7 +42,7 @@ class SAXException(Exception): ...@@ -42,7 +42,7 @@ class SAXException(Exception):
# ===== SAXPARSEEXCEPTION ===== # ===== SAXPARSEEXCEPTION =====
class SAXParseException(SAXException): class SAXParseException(SAXException):
"""Encapsulate an XML parse error or warning. """Encapsulate an XML parse error or warning.
This exception will include information for locating the error in This exception will include information for locating the error in
...@@ -62,7 +62,7 @@ class SAXParseException(SAXException): ...@@ -62,7 +62,7 @@ class SAXParseException(SAXException):
def getColumnNumber(self): def getColumnNumber(self):
"""The column number of the end of the text where the exception """The column number of the end of the text where the exception
occurred.""" occurred."""
return self._locator.getColumnNumber() return self._locator.getColumnNumber()
def getLineNumber(self): def getLineNumber(self):
......
...@@ -9,7 +9,7 @@ from xml.sax._exceptions import * ...@@ -9,7 +9,7 @@ from xml.sax._exceptions import *
try: try:
from xml.parsers import expat from xml.parsers import expat
except ImportError: except ImportError:
raise SAXReaderNotAvailable("expat not supported",None) raise SAXReaderNotAvailable("expat not supported",None)
from xml.sax import xmlreader, saxutils, handler from xml.sax import xmlreader, saxutils, handler
AttributesImpl = xmlreader.AttributesImpl AttributesImpl = xmlreader.AttributesImpl
...@@ -39,12 +39,12 @@ class ExpatParser(xmlreader.IncrementalParser, xmlreader.Locator): ...@@ -39,12 +39,12 @@ class ExpatParser(xmlreader.IncrementalParser, xmlreader.Locator):
self._source = source self._source = source
self.reset() self.reset()
self._cont_handler.setDocumentLocator(self) self._cont_handler.setDocumentLocator(self)
xmlreader.IncrementalParser.parse(self, source) xmlreader.IncrementalParser.parse(self, source)
def prepareParser(self, source): def prepareParser(self, source):
if source.getSystemId() != None: if source.getSystemId() != None:
self._parser.SetBase(source.getSystemId()) self._parser.SetBase(source.getSystemId())
def getFeature(self, name): def getFeature(self, name):
if name == handler.feature_namespaces: if name == handler.feature_namespaces:
return self._namespaces return self._namespaces
...@@ -91,7 +91,7 @@ class ExpatParser(xmlreader.IncrementalParser, xmlreader.Locator): ...@@ -91,7 +91,7 @@ class ExpatParser(xmlreader.IncrementalParser, xmlreader.Locator):
self.feed("", isFinal = 1) self.feed("", isFinal = 1)
self._cont_handler.endDocument() self._cont_handler.endDocument()
self._parsing = 0 self._parsing = 0
def reset(self): def reset(self):
if self._namespaces: if self._namespaces:
self._parser = expat.ParserCreate(None, " ") self._parser = expat.ParserCreate(None, " ")
...@@ -109,17 +109,17 @@ class ExpatParser(xmlreader.IncrementalParser, xmlreader.Locator): ...@@ -109,17 +109,17 @@ class ExpatParser(xmlreader.IncrementalParser, xmlreader.Locator):
self._parser.NotationDeclHandler = self.notation_decl self._parser.NotationDeclHandler = self.notation_decl
self._parser.StartNamespaceDeclHandler = self.start_namespace_decl self._parser.StartNamespaceDeclHandler = self.start_namespace_decl
self._parser.EndNamespaceDeclHandler = self.end_namespace_decl self._parser.EndNamespaceDeclHandler = self.end_namespace_decl
# self._parser.CommentHandler = # self._parser.CommentHandler =
# self._parser.StartCdataSectionHandler = # self._parser.StartCdataSectionHandler =
# self._parser.EndCdataSectionHandler = # self._parser.EndCdataSectionHandler =
# self._parser.DefaultHandler = # self._parser.DefaultHandler =
# self._parser.DefaultHandlerExpand = # self._parser.DefaultHandlerExpand =
# self._parser.NotStandaloneHandler = # self._parser.NotStandaloneHandler =
self._parser.ExternalEntityRefHandler = self.external_entity_ref self._parser.ExternalEntityRefHandler = self.external_entity_ref
self._parsing = 0 self._parsing = 0
self._entity_stack = [] self._entity_stack = []
# Locator methods # Locator methods
def getColumnNumber(self): def getColumnNumber(self):
...@@ -133,7 +133,7 @@ class ExpatParser(xmlreader.IncrementalParser, xmlreader.Locator): ...@@ -133,7 +133,7 @@ class ExpatParser(xmlreader.IncrementalParser, xmlreader.Locator):
def getSystemId(self): def getSystemId(self):
return self._source.getSystemId() return self._source.getSystemId()
# event handlers # event handlers
def start_element(self, name, attrs): def start_element(self, name, attrs):
self._cont_handler.startElement(name, AttributesImpl(attrs)) self._cont_handler.startElement(name, AttributesImpl(attrs))
...@@ -158,14 +158,14 @@ class ExpatParser(xmlreader.IncrementalParser, xmlreader.Locator): ...@@ -158,14 +158,14 @@ class ExpatParser(xmlreader.IncrementalParser, xmlreader.Locator):
newattrs[apair] = value newattrs[apair] = value
self._cont_handler.startElementNS(pair, None, self._cont_handler.startElementNS(pair, None,
AttributesNSImpl(newattrs, {})) AttributesNSImpl(newattrs, {}))
def end_element_ns(self, name): def end_element_ns(self, name):
pair = string.split(name) pair = string.split(name)
if len(pair) == 1: if len(pair) == 1:
pair = (None, name) pair = (None, name)
self._cont_handler.endElementNS(pair, None) self._cont_handler.endElementNS(pair, None)
# this is not used (call directly to ContentHandler) # this is not used (call directly to ContentHandler)
...@@ -181,7 +181,7 @@ class ExpatParser(xmlreader.IncrementalParser, xmlreader.Locator): ...@@ -181,7 +181,7 @@ class ExpatParser(xmlreader.IncrementalParser, xmlreader.Locator):
def end_namespace_decl(self, prefix): def end_namespace_decl(self, prefix):
self._cont_handler.endPrefixMapping(prefix) self._cont_handler.endPrefixMapping(prefix)
def unparsed_entity_decl(self, name, base, sysid, pubid, notation_name): def unparsed_entity_decl(self, name, base, sysid, pubid, notation_name):
self._dtd_handler.unparsedEntityDecl(name, pubid, sysid, notation_name) self._dtd_handler.unparsedEntityDecl(name, pubid, sysid, notation_name)
...@@ -193,7 +193,7 @@ class ExpatParser(xmlreader.IncrementalParser, xmlreader.Locator): ...@@ -193,7 +193,7 @@ class ExpatParser(xmlreader.IncrementalParser, xmlreader.Locator):
source = saxutils.prepare_input_source(source, source = saxutils.prepare_input_source(source,
self._source.getSystemId() or self._source.getSystemId() or
"") "")
self._entity_stack.append((self._parser, self._source)) self._entity_stack.append((self._parser, self._source))
self._parser = self._parser.ExternalEntityParserCreate(context) self._parser = self._parser.ExternalEntityParserCreate(context)
self._source = source self._source = source
...@@ -206,12 +206,12 @@ class ExpatParser(xmlreader.IncrementalParser, xmlreader.Locator): ...@@ -206,12 +206,12 @@ class ExpatParser(xmlreader.IncrementalParser, xmlreader.Locator):
(self._parser, self._source) = self._entity_stack[-1] (self._parser, self._source) = self._entity_stack[-1]
del self._entity_stack[-1] del self._entity_stack[-1]
return 1 return 1
# --- # ---
def create_parser(*args, **kwargs): def create_parser(*args, **kwargs):
return apply(ExpatParser, args, kwargs) return apply(ExpatParser, args, kwargs)
# --- # ---
if __name__ == "__main__": if __name__ == "__main__":
......
...@@ -38,10 +38,10 @@ class ErrorHandler: ...@@ -38,10 +38,10 @@ class ErrorHandler:
raise exception raise exception
def warning(self, exception): def warning(self, exception):
"Handle a warning." "Handle a warning."
print exception print exception
# ===== CONTENTHANDLER ===== # ===== CONTENTHANDLER =====
class ContentHandler: class ContentHandler:
...@@ -53,7 +53,7 @@ class ContentHandler: ...@@ -53,7 +53,7 @@ class ContentHandler:
def __init__(self): def __init__(self):
self._locator = None self._locator = None
def setDocumentLocator(self, locator): def setDocumentLocator(self, locator):
"""Called by the parser to give the application a locator for """Called by the parser to give the application a locator for
locating the origin of document events. locating the origin of document events.
...@@ -71,22 +71,22 @@ class ContentHandler: ...@@ -71,22 +71,22 @@ class ContentHandler:
character content that does not match an application's character content that does not match an application's
business rules). The information returned by the locator is business rules). The information returned by the locator is
probably not sufficient for use with a search engine. probably not sufficient for use with a search engine.
Note that the locator will return correct information only Note that the locator will return correct information only
during the invocation of the events in this interface. The during the invocation of the events in this interface. The
application should not attempt to use it at any other time.""" application should not attempt to use it at any other time."""
self._locator = locator self._locator = locator
def startDocument(self): def startDocument(self):
"""Receive notification of the beginning of a document. """Receive notification of the beginning of a document.
The SAX parser will invoke this method only once, before any The SAX parser will invoke this method only once, before any
other methods in this interface or in DTDHandler (except for other methods in this interface or in DTDHandler (except for
setDocumentLocator).""" setDocumentLocator)."""
def endDocument(self): def endDocument(self):
"""Receive notification of the end of a document. """Receive notification of the end of a document.
The SAX parser will invoke this method only once, and it will The SAX parser will invoke this method only once, and it will
be the last method invoked during the parse. The parser shall be the last method invoked during the parse. The parser shall
not invoke this method until it has either abandoned parsing not invoke this method until it has either abandoned parsing
...@@ -95,13 +95,13 @@ class ContentHandler: ...@@ -95,13 +95,13 @@ class ContentHandler:
def startPrefixMapping(self, prefix, uri): def startPrefixMapping(self, prefix, uri):
"""Begin the scope of a prefix-URI Namespace mapping. """Begin the scope of a prefix-URI Namespace mapping.
The information from this event is not necessary for normal The information from this event is not necessary for normal
Namespace processing: the SAX XML reader will automatically Namespace processing: the SAX XML reader will automatically
replace prefixes for element and attribute names when the replace prefixes for element and attribute names when the
http://xml.org/sax/features/namespaces feature is true (the http://xml.org/sax/features/namespaces feature is true (the
default). default).
There are cases, however, when applications need to use There are cases, however, when applications need to use
prefixes in character data or in attribute values, where they prefixes in character data or in attribute values, where they
cannot safely be expanded automatically; the cannot safely be expanded automatically; the
...@@ -118,7 +118,7 @@ class ContentHandler: ...@@ -118,7 +118,7 @@ class ContentHandler:
def endPrefixMapping(self, prefix): def endPrefixMapping(self, prefix):
"""End the scope of a prefix-URI mapping. """End the scope of a prefix-URI mapping.
See startPrefixMapping for details. This event will always See startPrefixMapping for details. This event will always
occur after the corresponding endElement event, but the order occur after the corresponding endElement event, but the order
of endPrefixMapping events is not otherwise guaranteed.""" of endPrefixMapping events is not otherwise guaranteed."""
...@@ -151,10 +151,10 @@ class ContentHandler: ...@@ -151,10 +151,10 @@ class ContentHandler:
The name parameter contains the name of the element type, just The name parameter contains the name of the element type, just
as with the startElementNS event.""" as with the startElementNS event."""
def characters(self, content): def characters(self, content):
"""Receive notification of character data. """Receive notification of character data.
The Parser will call this method to report each chunk of The Parser will call this method to report each chunk of
character data. SAX parsers may return all contiguous character data. SAX parsers may return all contiguous
character data in a single chunk, or they may split it into character data in a single chunk, or they may split it into
...@@ -164,24 +164,24 @@ class ContentHandler: ...@@ -164,24 +164,24 @@ class ContentHandler:
def ignorableWhitespace(self, whitespace): def ignorableWhitespace(self, whitespace):
"""Receive notification of ignorable whitespace in element content. """Receive notification of ignorable whitespace in element content.
Validating Parsers must use this method to report each chunk Validating Parsers must use this method to report each chunk
of ignorable whitespace (see the W3C XML 1.0 recommendation, of ignorable whitespace (see the W3C XML 1.0 recommendation,
section 2.10): non-validating parsers may also use this method section 2.10): non-validating parsers may also use this method
if they are capable of parsing and using content models. if they are capable of parsing and using content models.
SAX parsers may return all contiguous whitespace in a single SAX parsers may return all contiguous whitespace in a single
chunk, or they may split it into several chunks; however, all chunk, or they may split it into several chunks; however, all
of the characters in any single event must come from the same of the characters in any single event must come from the same
external entity, so that the Locator provides useful external entity, so that the Locator provides useful
information. information.
The application must not attempt to read from the array The application must not attempt to read from the array
outside of the specified range.""" outside of the specified range."""
def processingInstruction(self, target, data): def processingInstruction(self, target, data):
"""Receive notification of a processing instruction. """Receive notification of a processing instruction.
The Parser will invoke this method once for each processing The Parser will invoke this method once for each processing
instruction found: note that processing instructions may occur instruction found: note that processing instructions may occur
before or after the main document element. before or after the main document element.
...@@ -192,7 +192,7 @@ class ContentHandler: ...@@ -192,7 +192,7 @@ class ContentHandler:
def skippedEntity(self, name): def skippedEntity(self, name):
"""Receive notification of a skipped entity. """Receive notification of a skipped entity.
The Parser will invoke this method once for each entity The Parser will invoke this method once for each entity
skipped. Non-validating processors may skip entities if they skipped. Non-validating processors may skip entities if they
have not seen the declarations (because, for example, the have not seen the declarations (because, for example, the
...@@ -202,7 +202,7 @@ class ContentHandler: ...@@ -202,7 +202,7 @@ class ContentHandler:
http://xml.org/sax/features/external-parameter-entities http://xml.org/sax/features/external-parameter-entities
properties.""" properties."""
# ===== DTDHandler ===== # ===== DTDHandler =====
class DTDHandler: class DTDHandler:
...@@ -217,16 +217,16 @@ class DTDHandler: ...@@ -217,16 +217,16 @@ class DTDHandler:
def unparsedEntityDecl(self, name, publicId, systemId, ndata): def unparsedEntityDecl(self, name, publicId, systemId, ndata):
"Handle an unparsed entity declaration event." "Handle an unparsed entity declaration event."
# ===== ENTITYRESOLVER ===== # ===== ENTITYRESOLVER =====
class EntityResolver: class EntityResolver:
"""Basic interface for resolving entities. If you create an object """Basic interface for resolving entities. If you create an object
implementing this interface, then register the object with your implementing this interface, then register the object with your
Parser, the parser will call the method in your object to Parser, the parser will call the method in your object to
resolve all external entities. Note that DefaultHandler implements resolve all external entities. Note that DefaultHandler implements
this interface with the default behaviour.""" this interface with the default behaviour."""
def resolveEntity(self, publicId, systemId): def resolveEntity(self, publicId, systemId):
"""Resolve the system identifier of an entity and return either """Resolve the system identifier of an entity and return either
the system identifier to read from as a string, or an InputSource the system identifier to read from as a string, or an InputSource
......
...@@ -12,7 +12,7 @@ _StringTypes = [types.StringType, types.UnicodeType] ...@@ -12,7 +12,7 @@ _StringTypes = [types.StringType, types.UnicodeType]
def escape(data, entities={}): def escape(data, entities={}):
"""Escape &, <, and > in a string of data. """Escape &, <, and > in a string of data.
You can escape other strings of data by passing a dictionary as You can escape other strings of data by passing a dictionary as
the optional entities parameter. The keys and values must all be the optional entities parameter. The keys and values must all be
strings; each key will be replaced with its corresponding value. strings; each key will be replaced with its corresponding value.
""" """
...@@ -20,7 +20,7 @@ def escape(data, entities={}): ...@@ -20,7 +20,7 @@ def escape(data, entities={}):
data = data.replace("<", "&lt;") data = data.replace("<", "&lt;")
data = data.replace(">", "&gt;") data = data.replace(">", "&gt;")
for chars, entity in entities.items(): for chars, entity in entities.items():
data = data.replace(chars, entity) data = data.replace(chars, entity)
return data return data
...@@ -57,7 +57,7 @@ class XMLGenerator(handler.ContentHandler): ...@@ -57,7 +57,7 @@ class XMLGenerator(handler.ContentHandler):
for (name, value) in attrs.items(): for (name, value) in attrs.items():
self._out.write(' %s="%s"' % (name, escape(value))) self._out.write(' %s="%s"' % (name, escape(value)))
self._out.write('>') self._out.write('>')
def endElement(self, name): def endElement(self, name):
self._out.write('</%s>' % name) self._out.write('</%s>' % name)
...@@ -73,7 +73,7 @@ class XMLGenerator(handler.ContentHandler): ...@@ -73,7 +73,7 @@ class XMLGenerator(handler.ContentHandler):
for pair in self._undeclared_ns_maps: for pair in self._undeclared_ns_maps:
self._out.write(' xmlns:%s="%s"' % pair) self._out.write(' xmlns:%s="%s"' % pair)
self._undeclared_ns_maps = [] self._undeclared_ns_maps = []
for (name, value) in attrs.items(): for (name, value) in attrs.items():
name = self._current_context[name[0]] + ":" + name[1] name = self._current_context[name[0]] + ":" + name[1]
self._out.write(' %s="%s"' % (name, escape(value))) self._out.write(' %s="%s"' % (name, escape(value)))
...@@ -85,7 +85,7 @@ class XMLGenerator(handler.ContentHandler): ...@@ -85,7 +85,7 @@ class XMLGenerator(handler.ContentHandler):
else: else:
name = self._current_context[name[0]] + ":" + name[1] name = self._current_context[name[0]] + ":" + name[1]
self._out.write('</%s>' % name) self._out.write('</%s>' % name)
def characters(self, content): def characters(self, content):
self._out.write(escape(content)) self._out.write(escape(content))
...@@ -107,7 +107,7 @@ class XMLFilterBase(xmlreader.XMLReader): ...@@ -107,7 +107,7 @@ class XMLFilterBase(xmlreader.XMLReader):
def __init__(self, parent = None): def __init__(self, parent = None):
xmlreader.XMLReader.__init__(self) xmlreader.XMLReader.__init__(self)
self._parent = parent self._parent = parent
# ErrorHandler methods # ErrorHandler methods
def error(self, exception): def error(self, exception):
...@@ -210,7 +210,7 @@ class XMLFilterBase(xmlreader.XMLReader): ...@@ -210,7 +210,7 @@ class XMLFilterBase(xmlreader.XMLReader):
def prepare_input_source(source, base = ""): def prepare_input_source(source, base = ""):
"""This function takes an InputSource and an optional base URL and """This function takes an InputSource and an optional base URL and
returns a fully resolved InputSource object ready for reading.""" returns a fully resolved InputSource object ready for reading."""
if type(source) in _StringTypes: if type(source) in _StringTypes:
source = xmlreader.InputSource(source) source = xmlreader.InputSource(source)
elif hasattr(source, "read"): elif hasattr(source, "read"):
...@@ -229,7 +229,7 @@ def prepare_input_source(source, base = ""): ...@@ -229,7 +229,7 @@ def prepare_input_source(source, base = ""):
else: else:
source.setSystemId(urlparse.urljoin(base, sysid)) source.setSystemId(urlparse.urljoin(base, sysid))
f = urllib.urlopen(source.getSystemId()) f = urllib.urlopen(source.getSystemId())
source.setByteStream(f) source.setByteStream(f)
return source return source
...@@ -6,7 +6,7 @@ import handler ...@@ -6,7 +6,7 @@ import handler
# ===== XMLREADER ===== # ===== XMLREADER =====
class XMLReader: class XMLReader:
"""Interface for reading an XML document using callbacks. """Interface for reading an XML document using callbacks.
XMLReader is the interface that an XML parser's SAX2 driver must XMLReader is the interface that an XML parser's SAX2 driver must
implement. This interface allows an application to set and query implement. This interface allows an application to set and query
...@@ -17,7 +17,7 @@ class XMLReader: ...@@ -17,7 +17,7 @@ class XMLReader:
methods must not return until parsing is complete, and readers methods must not return until parsing is complete, and readers
must wait for an event-handler callback to return before reporting must wait for an event-handler callback to return before reporting
the next event.""" the next event."""
def __init__(self): def __init__(self):
self._cont_handler = handler.ContentHandler() self._cont_handler = handler.ContentHandler()
self._dtd_handler = handler.DTDHandler() self._dtd_handler = handler.DTDHandler()
...@@ -35,11 +35,11 @@ class XMLReader: ...@@ -35,11 +35,11 @@ class XMLReader:
def setContentHandler(self, handler): def setContentHandler(self, handler):
"Registers a new object to receive document content events." "Registers a new object to receive document content events."
self._cont_handler = handler self._cont_handler = handler
def getDTDHandler(self): def getDTDHandler(self):
"Returns the current DTD handler." "Returns the current DTD handler."
return self._dtd_handler return self._dtd_handler
def setDTDHandler(self, handler): def setDTDHandler(self, handler):
"Register an object to receive basic DTD-related events." "Register an object to receive basic DTD-related events."
self._dtd_handler = handler self._dtd_handler = handler
...@@ -47,7 +47,7 @@ class XMLReader: ...@@ -47,7 +47,7 @@ class XMLReader:
def getEntityResolver(self): def getEntityResolver(self):
"Returns the current EntityResolver." "Returns the current EntityResolver."
return self._ent_handler return self._ent_handler
def setEntityResolver(self, resolver): def setEntityResolver(self, resolver):
"Register an object to resolve external entities." "Register an object to resolve external entities."
self._ent_handler = resolver self._ent_handler = resolver
...@@ -55,20 +55,20 @@ class XMLReader: ...@@ -55,20 +55,20 @@ class XMLReader:
def getErrorHandler(self): def getErrorHandler(self):
"Returns the current ErrorHandler." "Returns the current ErrorHandler."
return self._err_handler return self._err_handler
def setErrorHandler(self, handler): def setErrorHandler(self, handler):
"Register an object to receive error-message events." "Register an object to receive error-message events."
self._err_handler = handler self._err_handler = handler
def setLocale(self, locale): def setLocale(self, locale):
"""Allow an application to set the locale for errors and warnings. """Allow an application to set the locale for errors and warnings.
SAX parsers are not required to provide localization for errors SAX parsers are not required to provide localization for errors
and warnings; if they cannot support the requested locale, and warnings; if they cannot support the requested locale,
however, they must throw a SAX exception. Applications may however, they must throw a SAX exception. Applications may
request a locale change in the middle of a parse.""" request a locale change in the middle of a parse."""
raise SAXNotSupportedException("Locale support not implemented") raise SAXNotSupportedException("Locale support not implemented")
def getFeature(self, name): def getFeature(self, name):
"Looks up and returns the state of a SAX2 feature." "Looks up and returns the state of a SAX2 feature."
raise SAXNotRecognizedException("Feature '%s' not recognized" % name) raise SAXNotRecognizedException("Feature '%s' not recognized" % name)
...@@ -112,7 +112,7 @@ class IncrementalParser(XMLReader): ...@@ -112,7 +112,7 @@ class IncrementalParser(XMLReader):
def parse(self, source): def parse(self, source):
import saxutils import saxutils
source = saxutils.prepare_input_source(source) source = saxutils.prepare_input_source(source)
self.prepareParser(source) self.prepareParser(source)
file = source.getByteStream() file = source.getByteStream()
buffer = file.read(self._bufsize) buffer = file.read(self._bufsize)
...@@ -121,7 +121,7 @@ class IncrementalParser(XMLReader): ...@@ -121,7 +121,7 @@ class IncrementalParser(XMLReader):
buffer = file.read(self._bufsize) buffer = file.read(self._bufsize)
self.close() self.close()
def feed(self, data): def feed(self, data):
"""This method gives the raw XML data in the data parameter to """This method gives the raw XML data in the data parameter to
the parser and makes it parse the data, emitting the the parser and makes it parse the data, emitting the
corresponding events. It is allowed for XML constructs to be corresponding events. It is allowed for XML constructs to be
...@@ -238,7 +238,7 @@ class InputSource: ...@@ -238,7 +238,7 @@ class InputSource:
"""Set the byte stream (a Python file-like object which does """Set the byte stream (a Python file-like object which does
not perform byte-to-character conversion) for this input not perform byte-to-character conversion) for this input
source. source.
The SAX parser will ignore this if there is also a character The SAX parser will ignore this if there is also a character
stream specified, but it will use a byte stream in preference stream specified, but it will use a byte stream in preference
to opening a URI connection itself. to opening a URI connection itself.
...@@ -249,16 +249,16 @@ class InputSource: ...@@ -249,16 +249,16 @@ class InputSource:
def getByteStream(self): def getByteStream(self):
"""Get the byte stream for this input source. """Get the byte stream for this input source.
The getEncoding method will return the character encoding for The getEncoding method will return the character encoding for
this byte stream, or None if unknown.""" this byte stream, or None if unknown."""
return self.__bytefile return self.__bytefile
def setCharacterStream(self, charfile): def setCharacterStream(self, charfile):
"""Set the character stream for this input source. (The stream """Set the character stream for this input source. (The stream
must be a Python 1.6 Unicode-wrapped file-like that performs must be a Python 1.6 Unicode-wrapped file-like that performs
conversion to Unicode strings.) conversion to Unicode strings.)
If there is a character stream specified, the SAX parser will If there is a character stream specified, the SAX parser will
ignore any byte stream and will not attempt to open a URI ignore any byte stream and will not attempt to open a URI
connection to the system identifier.""" connection to the system identifier."""
...@@ -267,11 +267,11 @@ class InputSource: ...@@ -267,11 +267,11 @@ class InputSource:
def getCharacterStream(self): def getCharacterStream(self):
"Get the character stream for this input source." "Get the character stream for this input source."
return self.__charfile return self.__charfile
# ===== ATTRIBUTESIMPL ===== # ===== ATTRIBUTESIMPL =====
class AttributesImpl: class AttributesImpl:
def __init__(self, attrs): def __init__(self, attrs):
"""Non-NS-aware implementation. """Non-NS-aware implementation.
...@@ -298,13 +298,13 @@ class AttributesImpl: ...@@ -298,13 +298,13 @@ class AttributesImpl:
def getQNameByName(self, name): def getQNameByName(self, name):
if not self._attrs.has_key(name): if not self._attrs.has_key(name):
raise KeyError raise KeyError
return name return name
def getNames(self): def getNames(self):
return self._attrs.keys() return self._attrs.keys()
def getQNames(self): def getQNames(self):
return self._attrs.keys() return self._attrs.keys()
def __len__(self): def __len__(self):
return len(self._attrs) return len(self._attrs)
...@@ -333,7 +333,7 @@ class AttributesImpl: ...@@ -333,7 +333,7 @@ class AttributesImpl:
# ===== ATTRIBUTESNSIMPL ===== # ===== ATTRIBUTESNSIMPL =====
class AttributesNSImpl(AttributesImpl): class AttributesNSImpl(AttributesImpl):
def __init__(self, attrs, qnames): def __init__(self, attrs, qnames):
"""NS-aware implementation. """NS-aware implementation.
...@@ -346,25 +346,25 @@ class AttributesNSImpl(AttributesImpl): ...@@ -346,25 +346,25 @@ class AttributesNSImpl(AttributesImpl):
for (nsname, qname) in self._qnames.items(): for (nsname, qname) in self._qnames.items():
if qname == name: if qname == name:
return self._attrs[nsname] return self._attrs[nsname]
raise KeyError raise KeyError
def getNameByQName(self, name): def getNameByQName(self, name):
for (nsname, qname) in self._qnames.items(): for (nsname, qname) in self._qnames.items():
if qname == name: if qname == name:
return nsname return nsname
raise KeyError raise KeyError
def getQNameByName(self, name): def getQNameByName(self, name):
return self._qnames[name] return self._qnames[name]
def getQNames(self): def getQNames(self):
return self._qnames.values() return self._qnames.values()
def copy(self): def copy(self):
return self.__class__(self._attrs, self._qnames) return self.__class__(self._attrs, self._qnames)
def _test(): def _test():
XMLReader() XMLReader()
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment