/Doc/includes/minidom-example.py

http://unladen-swallow.googlecode.com/ · Python · 64 lines · 52 code · 12 blank · 0 comment · 5 complexity · 82cddf85569484594d61425d4e91b806 MD5 · raw file

  1. import xml.dom.minidom
  2. document = """\
  3. <slideshow>
  4. <title>Demo slideshow</title>
  5. <slide><title>Slide title</title>
  6. <point>This is a demo</point>
  7. <point>Of a program for processing slides</point>
  8. </slide>
  9. <slide><title>Another demo slide</title>
  10. <point>It is important</point>
  11. <point>To have more than</point>
  12. <point>one slide</point>
  13. </slide>
  14. </slideshow>
  15. """
  16. dom = xml.dom.minidom.parseString(document)
  17. def getText(nodelist):
  18. rc = ""
  19. for node in nodelist:
  20. if node.nodeType == node.TEXT_NODE:
  21. rc = rc + node.data
  22. return rc
  23. def handleSlideshow(slideshow):
  24. print "<html>"
  25. handleSlideshowTitle(slideshow.getElementsByTagName("title")[0])
  26. slides = slideshow.getElementsByTagName("slide")
  27. handleToc(slides)
  28. handleSlides(slides)
  29. print "</html>"
  30. def handleSlides(slides):
  31. for slide in slides:
  32. handleSlide(slide)
  33. def handleSlide(slide):
  34. handleSlideTitle(slide.getElementsByTagName("title")[0])
  35. handlePoints(slide.getElementsByTagName("point"))
  36. def handleSlideshowTitle(title):
  37. print "<title>%s</title>" % getText(title.childNodes)
  38. def handleSlideTitle(title):
  39. print "<h2>%s</h2>" % getText(title.childNodes)
  40. def handlePoints(points):
  41. print "<ul>"
  42. for point in points:
  43. handlePoint(point)
  44. print "</ul>"
  45. def handlePoint(point):
  46. print "<li>%s</li>" % getText(point.childNodes)
  47. def handleToc(slides):
  48. for slide in slides:
  49. title = slide.getElementsByTagName("title")[0]
  50. print "<p>%s</p>" % getText(title.childNodes)
  51. handleSlideshow(dom)