home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 15 / AACD15.ISO / AACD / Programming / Python2 / Demo / xml / roundtrip.py < prev    next >
Encoding:
Python Source  |  2000-10-25  |  1.2 KB  |  46 lines

  1. """
  2. A simple demo that reads in an XML document and spits out an equivalent,
  3. but not necessarily identical, document.
  4. """
  5.  
  6. import sys, string
  7.  
  8. from xml.sax import saxutils, handler, make_parser
  9.  
  10. # --- The ContentHandler
  11.  
  12. class 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.  
  43. parser = make_parser()
  44. parser.setContentHandler(ContentGenerator())
  45. parser.parse(sys.argv[1])
  46.