PageRenderTime 251ms CodeModel.GetById 149ms app.highlight 4ms RepoModel.GetById 96ms app.codeStats 1ms

/Demo/xml/roundtrip.py

http://unladen-swallow.googlecode.com/
Python | 45 lines | 24 code | 14 blank | 7 comment | 2 complexity | f8fc9e48e4af6b3c4bfdb691abb2f3ee MD5 | raw file
 1"""
 2A simple demo that reads in an XML document and spits out an equivalent,
 3but not necessarily identical, document.
 4"""
 5
 6import sys, string
 7
 8from xml.sax import saxutils, handler, make_parser
 9
10# --- The ContentHandler
11
12class ContentGenerator(handler.ContentHandler):
13
14    def __init__(self, out = sys.stdout):
15        handler.ContentHandler.__init__(self)
16        self._out = out
17
18    # ContentHandler methods
19
20    def startDocument(self):
21        self._out.write('<?xml version="1.0" encoding="iso-8859-1"?>\n')
22
23    def startElement(self, name, attrs):
24        self._out.write('<' + name)
25        for (name, value) in attrs.items():
26            self._out.write(' %s="%s"' % (name, saxutils.escape(value)))
27        self._out.write('>')
28
29    def endElement(self, name):
30        self._out.write('</%s>' % name)
31
32    def characters(self, content):
33        self._out.write(saxutils.escape(content))
34
35    def ignorableWhitespace(self, content):
36        self._out.write(content)
37
38    def processingInstruction(self, target, data):
39        self._out.write('<?%s %s?>' % (target, data))
40
41# --- The main program
42
43parser = make_parser()
44parser.setContentHandler(ContentGenerator())
45parser.parse(sys.argv[1])