📄 writer.py
字号:
"""SAX document handlers that support output generation of XML, SGML,
and XHTML.
This module provides three different groups of objects: the actual SAX
document handlers that drive the output, DTD information containers,
and syntax descriptors (of limited public use in most cases).
Output Drivers
--------------
The output drivers conform to the SAX C<DocumentHandler> protocol.
They can be used anywhere a C<DocumentHandler> is used. Two drivers
are provided: a `basic' driver which creates a fairly minimal output
without much intelligence, and a `pretty-printing' driver that
performs pretty-printing with nice indentation and the like. Both can
optionally make use of DTD information and syntax objects.
DTD Information Containers
--------------------------
Each DTD information object provides an attribute C<syntax> which
describes the expected output syntax; an alternate can be provided to
the output drivers if desired.
Syntax Descriptors
------------------
Syntax descriptor objects provide several attributes which describe
the various lexical components of XML & SGML markup. The attributes
have names that reflect the shorthand notation from the SGML world,
but the values are strings which give the appropriate characters for
the markup language being described. The one addition is the
C<empty_stagc> attribute which should be used to end the start tag of
elements which have no content. This is needed to properly support
XML and XHTML.
"""
__version__ = '$Revision$'
import string
import xml.parsers.xmlproc.dtdparser
import xml.parsers.xmlproc.xmlapp
from xml.sax.saxutils import escape
DEFAULT_LINELENGTH = 74
class Syntax:
com = "--" # comment start or end
cro = "&#" # character reference open
refc = ";" # reference close
dso = "[" # declaration subset open
dsc = "]" # declaration subset close
ero = "&" # entity reference open
lit = '"' # literal start or end
lita = "'" # literal start or end (alternative)
mdo = "<!" # markup declaration open
mdc = ">" # markup declaration close
msc = "]]" # marked section close
pio = "<?" # processing instruciton open
stago = "<" # start tag open
etago = "</" # end tag open
tagc = ">" # tag close
vi = "=" # value indicator
def __init__(self):
if self.__class__ is Syntax:
raise RuntimeError, "Syntax must be subclassed to be used!"
class SGMLSyntax(Syntax):
empty_stagc = ">"
pic = ">" # processing instruction close
net = "/" # null end tag
class XMLSyntax(Syntax):
empty_stagc = "/>"
pic = "?>" # processing instruction close
net = None # null end tag not supported
class XHTMLSyntax(XMLSyntax):
empty_stagc = " />"
class DoctypeInfo:
syntax = XMLSyntax()
fpi = None
sysid = None
def __init__(self):
self.__empties = {}
self.__elements_only = {}
self.__attribs = {}
def is_empty(self, gi):
return self.__empties.has_key(gi)
def get_empties_list(self):
return self.__empties.keys()
def has_element_content(self, gi):
return self.__elements_only.has_key(gi)
def get_element_containers_list(self):
return self.__elements_only.keys()
def get_attributes_list(self, gi):
return self.__attribs.get(gi, {}).keys()
def get_attribute_info(self, gi, attr):
return self.__attribs[gi][attr]
def add_empty(self, gi):
self.__empties[gi] = 1
def add_element_container(self, gi):
self.__elements_only[gi] = gi
def add_attribute_defn(self, gi, attr, type, decl, default):
try:
d = self.__attribs[gi]
except KeyError:
d = self.__attribs[gi] = {}
if not d.has_key(attr):
d[attr] = (type, decl, default)
else:
print "<%s> attribute %s already defined" % (gi, attr)
def load_pubtext(self, pubtext):
raise NotImplementedError, "sublasses must implement load_pubtext()"
class _XMLDTDLoader(xml.parsers.xmlproc.xmlapp.DTDConsumer):
def __init__(self, info, parser):
self.info = info
xml.parsers.xmlproc.xmlapp.DTDConsumer.__init__(self, parser)
self.new_attribute = info.add_attribute_defn
def new_element_type(self, gi, model):
if model[0] == "|" and model[1][0] == ("#PCDATA", ""):
# no action required
pass
elif model == ("", [], ""):
self.info.add_empty(gi)
else:
self.info.add_element_container(gi)
class XMLDoctypeInfo(DoctypeInfo):
def load_pubtext(self, sysid):
parser = xml.parsers.xmlproc.dtdparser.DTDParser()
loader = _XMLDTDLoader(self, parser)
parser.set_dtd_consumer(loader)
parser.parse_resource(sysid)
class XHTMLDoctypeInfo(XMLDoctypeInfo):
# Bogus W3C cruft requires the extra space when terminating empty elements.
syntax = XHTMLSyntax()
class SGMLDoctypeInfo(DoctypeInfo):
syntax = SGMLSyntax()
import re
__element_prefix_search = re.compile("<!ELEMENT", re.IGNORECASE).search
__element_prefix_len = len("<!ELEMENT")
del re
def load_pubtext(self, sysid):
#
# Really should build a proper SGML DTD parser!
#
pubtext = open(sysid).read()
m = self.__element_prefix_search(pubtext)
while m:
pubtext = pubtext[m.end():]
if pubtext and pubtext[0] in string.whitespace:
pubtext = string.lstrip(pubtext)
else:
continue
gi, pubtext = string.split(pubtext, None, 1)
pubtext = string.lstrip(pubtext)
# maybe need to remove/collect tag occurance specifiers
# ...
raise NotImplementedError, "implementation incomplete"
#
m = self.__element_prefix_search(pubtext)
class XmlWriter:
"""Basic XML output handler."""
def __init__(self, fp, standalone=None, dtdinfo=None,
syntax=None, linelength=None):
self._offset = 0
self._packing = 0
self._flowing = 1
self._write = fp.write
self._dtdflowing = None
self._prefix = ''
self.__stack = []
self.__lang = None
self.__pending_content = 0
self.__pending_doctype = 1
self.__standalone = standalone
self.__dtdinfo = dtdinfo
if syntax is None:
if dtdinfo:
syntax = dtdinfo.syntax
else:
syntax = XMLSyntax()
self.__syntax = syntax
self.indentation = 0
self.indentEndTags = 0
if linelength is None:
self.lineLength = DEFAULT_LINELENGTH
else:
self.lineLength = linelength
def setDocumentLocator(self, locator):
self.locator = locator
def startDocument(self):
if self.__syntax.pic == "?>":
lit = self.__syntax.lit
s = '%sxml version=%s1.0%s encoding%s%siso-8859-1%s' % (
self.__syntax.pio, lit, lit, self.__syntax.vi, lit, lit)
if self.__standalone:
s = '%s standalone%s%s%s%s' % (
s, self.__syntax.vi, lit, self.__standalone, lit)
self._write("%s%s\n" % (s, self.__syntax.pic))
def endDocument(self):
if self.__stack:
raise RuntimeError, "open element stack cannot be empty on close"
def startElement(self, tag, attrs={}):
if self.__pending_doctype:
self.handle_doctype(tag)
self._check_pending_content()
self.__pushtag(tag)
self.__check_flowing(tag, attrs)
if attrs.has_key("xml:lang"):
self.__lang = attrs["xml:lang"]
del attrs["xml:lang"]
if self._packing:
prefix = ""
elif self._flowing:
prefix = self._prefix[:-self.indentation]
else:
prefix = ""
stag = "%s%s%s" % (prefix, self.__syntax.stago, tag)
prefix = "%s %s" % (prefix, (len(tag) * " "))
lit = self.__syntax.lit
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -