这个项目介绍的是如何使用XML来表示多种数据,以及如何使用适合XML或SAX的简单API来处理XML文件。这个项目的目标是通过一个描述各种网页和目录的XML文件生成一个完整的网站。
XML文件至少需要包括网站、目录、页面、名称、标题和内容。
下面是XML文件,website.xml:
<website>
<page name="index" title="Home page">
<h1>Welcome to my Home page</h1>
<p>Hi, there. My name is Mr.gumby,and this is my home page,here are some of my int:</p>
<ul>
<li><a href="interests/shouting.html">Shouting</a></li>
<li><a href="interests/sleeping.html">Sleeping</a></li>
<li><a href="interests/eating.html">Eating</a></li>
</ul>
</page>
<directory name="interests">
<page name="shouting" title="Shouting">
<h1>shouting page</h1>
<p>....</p>
</page>
<page name="sleeping" title="Sleeping">
<h1>sleeping page</h1>
<p>...</p>
</page>
<page name="eating" title="Eating">
<h1>Eating page</h1>
<p>....</p>
</page>
</directory>
</website>
在python中使用sax方式处理xml要使用入xml.sax模块中的parse函数,这个函数负责读取文件并且生成事件。还有xml.sax.handler中的ContentHandler类,parse('xxx.xml',xxxHandler),这里面的xxxHandler要继承上面的ContentHandler类, 然后这个parse函数在处理xml文件的时候,会调用xxxHandler中的startElement函数和endElement函数来一个xml中的标签的开始和结束,中间的过程使用一个名为characters的函数来处理标签内部的所有字符串。
实现代码:
from xml.sax.handler import ContentHandler
from xml.sax import parse
import os
class Dispatcher:
def dispatch(self, prefix, name, attrs=None):
mname = prefix + name.capitalize()
dname = 'default' + prefix.capitalize()
method = getattr(self, mname, None)
if callable(method): args = ()
else:
method = getattr(self, dname, None)
args = name,
if prefix == 'start': args += attrs,
if callable(method): method(*args)
def startElement(self, name, attrs):
self.dispatch('start', name, attrs)
def endElement(self, name):
self.dispatch('end', name)
class WebsiteConstructor(Dispatcher, ContentHandler):
passthrough = False
def __init__(self, directory):
self.directory = [directory]
self.ensureDirectory()
def ensureDirectory(self):
path = os.path.join(*self.directory)
if not os.path.isdir(path): os.makedirs(path)
def characters(self, chars):
if self.passthrough: self.out.write(chars)
def defaultStart(self, name, attrs): #处理XHTML
if self.passthrough:
self.out.write('<' + name)
for key, val in attrs.items():
self.out.write(' %s="%s"' %(key, val))
self.out.write('>')
def defaultEnd(self, name):
if self.passthrough:
self.out.write('</%s>' % name)
def startDirectory(self, attrs): #处理目录
self.directory.append(attrs['name'])
self.ensureDirectory()
def endDirectory(self):
self.directory.pop()
def startPage(self, attrs): #处理页面
filename = os.path.join(*self.directory + [attrs['name']+'.html'])
self.out = open(filename, 'w')
self.writeHeader(attrs['title'])
self.passthrough = True
def endPage(self):
print 'endPage'
self.passthrough = False
self.writeFooter()
self.out.close()
def writeHeader(self, title):
self.out.write('<html>\n <head>\n <title>')
self.out.write(title)
self.out.write('</title>\n </head>\n <body>\n')
def writeFooter(self):
self.out.write('\n </body>\n</html>\n')
parse('website.xml',WebsiteConstructor('public_html'))
执行结果:
生成下面的文件和目录:
1.public_html/
2.pubic_html/index.html
3.public_html/interests
4.public_html/interests/shouting.html
5.public_html/interests/sleeping.html
6.public_html/interests/eating.html