listing22-2.py 1.0 KB

1234567891011121314151617181920212223242526272829303132
  1. from xml.sax.handler import ContentHandler
  2. from xml.sax import parse
  3. class PageMaker(ContentHandler):
  4. passthrough = False
  5. def startElement(self, name, attrs):
  6. if name == 'page':
  7. self.passthrough = True
  8. self.out = open(attrs['name'] + '.html', 'w')
  9. self.out.write('<html><head>\n')
  10. self.out.write('<title>{}</title>\n'.format(attrs['title']))
  11. self.out.write('</head><body>\n')
  12. elif self.passthrough:
  13. self.out.write('<' + name)
  14. for key, val in attrs.items():
  15. self.out.write(' {}="{}"'.format(key, val))
  16. self.out.write('>')
  17. def endElement(self, name):
  18. if name == 'page':
  19. self.passthrough = False
  20. self.out.write('\n</body></html>\n')
  21. self.out.close()
  22. elif self.passthrough:
  23. self.out.write('</{}>'.format(name))
  24. def characters(self, chars):
  25. if self.passthrough: self.out.write(chars)
  26. parse('website.xml', PageMaker())