minidom-example.py 1.54 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
import xml.dom.minidom

document = """\
<slideshow>
<title>Demo slideshow</title>
<slide><title>Slide title</title>
<point>This is a demo</point>
<point>Of a program for processing slides</point>
</slide>

<slide><title>Another demo slide</title>
<point>It is important</point>
<point>To have more than</point>
<point>one slide</point>
</slide>
</slideshow>
"""

dom = xml.dom.minidom.parseString(document)

def getText(nodelist):
Benjamin Peterson's avatar
Benjamin Peterson committed
22
    rc = []
23 24
    for node in nodelist:
        if node.nodeType == node.TEXT_NODE:
Benjamin Peterson's avatar
Benjamin Peterson committed
25 26
            rc.append(node.data)
    return ''.join(rc)
27 28

def handleSlideshow(slideshow):
29
    print("<html>")
30 31 32 33
    handleSlideshowTitle(slideshow.getElementsByTagName("title")[0])
    slides = slideshow.getElementsByTagName("slide")
    handleToc(slides)
    handleSlides(slides)
34
    print("</html>")
35 36 37 38 39 40 41 42 43 44

def handleSlides(slides):
    for slide in slides:
        handleSlide(slide)

def handleSlide(slide):
    handleSlideTitle(slide.getElementsByTagName("title")[0])
    handlePoints(slide.getElementsByTagName("point"))

def handleSlideshowTitle(title):
45
    print("<title>%s</title>" % getText(title.childNodes))
46 47

def handleSlideTitle(title):
48
    print("<h2>%s</h2>" % getText(title.childNodes))
49 50

def handlePoints(points):
51
    print("<ul>")
52 53
    for point in points:
        handlePoint(point)
54
    print("</ul>")
55 56

def handlePoint(point):
57
    print("<li>%s</li>" % getText(point.childNodes))
58 59 60 61

def handleToc(slides):
    for slide in slides:
        title = slide.getElementsByTagName("title")[0]
62
        print("<p>%s</p>" % getText(title.childNodes))
63 64

handleSlideshow(dom)