/Demo/xml/roundtrip.py

http://unladen-swallow.googlecode.com/ · Python · 45 lines · 24 code · 14 blank · 7 comment · 1 complexity · f8fc9e48e4af6b3c4bfdb691abb2f3ee MD5 · raw file

  1. """
  2. A simple demo that reads in an XML document and spits out an equivalent,
  3. but not necessarily identical, document.
  4. """
  5. import sys, string
  6. from xml.sax import saxutils, handler, make_parser
  7. # --- The ContentHandler
  8. class ContentGenerator(handler.ContentHandler):
  9. def __init__(self, out = sys.stdout):
  10. handler.ContentHandler.__init__(self)
  11. self._out = out
  12. # ContentHandler methods
  13. def startDocument(self):
  14. self._out.write('<?xml version="1.0" encoding="iso-8859-1"?>\n')
  15. def startElement(self, name, attrs):
  16. self._out.write('<' + name)
  17. for (name, value) in attrs.items():
  18. self._out.write(' %s="%s"' % (name, saxutils.escape(value)))
  19. self._out.write('>')
  20. def endElement(self, name):
  21. self._out.write('</%s>' % name)
  22. def characters(self, content):
  23. self._out.write(saxutils.escape(content))
  24. def ignorableWhitespace(self, content):
  25. self._out.write(content)
  26. def processingInstruction(self, target, data):
  27. self._out.write('<?%s %s?>' % (target, data))
  28. # --- The main program
  29. parser = make_parser()
  30. parser.setContentHandler(ContentGenerator())
  31. parser.parse(sys.argv[1])