[XML-SIG] xml.sax.writer

Geir Ove Grønmo grove@infotek.no
25 Nov 1999 14:44:30 +0100


* Fred L. Drake, Jr.
|   I've just checked in the xml.sax.writer module, which defines a
| couple of SAX DocumentHandler-protocol classes that can be used to
| generate XML output.  There are two primary classes:
| 
|     XmlWriter -- basic XML generation
|     PrettyPrinter -- adds nice indentation

I've done something similar in xmlarch and GPS, but it's not as powerful
as the xml.sax.writer module.

When I developed GPS I created a in tutorial that showed how a user
could interact with groves and property sets. Since new versions are
released regularly and the behavior might have changed, I had to
manually run though the examples to make sure that the results of the
expressions were the same. This wasn't very convenient, so I developed a
tool that regenerated the tutorial.

One of the examples wrote an XML file to standard output using the
Prettifier class. [Un]fortunately the tutorial was an HTML file, so some
characters had to be escaped to be displayed correctly.

I solved this by writing a stream filter that escaped characters:

    class HTMLEscaper:
	escape_chars = {"<": "&lt;",
			"&": "&amp;"}

	def __init__(self, writer):
	    self.writer = writer

	def write(self, str):
	    newstr = str
	    for oldchars, newchars  in self.escape_chars.items():
		newstr = string.replace(newstr, oldchars, newchars)
	    self.writer.write(newstr)

	def flush(self):
	    self.writer.flush()

I believe this would be very useful to have in the xml.sax.writer module
as well. It should probably be solved by having a general Escaper class
and several subclasses that contained specific mappings.

All the best,
Geir O.