XML快速写网页-02
Posted 李嘉图杂文
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了XML快速写网页-02相关的知识,希望对你有一定的参考价值。
XML快速写网页-02
功能
根据XML自动生成文件目录,并快速生成完整的网页项目
完成程序(website.py)结构介绍
(1)分派器混合类(class Dispatcher)
a.在startElement被调用时,根据参数name(假设name为'foo')查找并调用这个事件的处理程序startFoo
b.endElement调用时,调用endFoo
c.不是特殊的处理程序(page,dirctory)就调用默认事件处理程序(defaultStart,defaultEnd)
(2)把首尾写入文件(writeHeader,writeFooter)
(3)各种事件处理程序
代码
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)
os.makedirs(path,exist_ok=True)
def characters(self,chars):
if self.passthrough:self.out.write(chars)
def defaultStart(self,name,attrs):
if self.passthrough:
self.out.write('<'+name)
for key,val in attrs.items():
self.out.write(' {}="{}"'.format(key,val))
self.out.write('>')
def defaultEnd(self,name):
if self.passthrough:
self.out.write('</{}>'.format(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):
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'))
结果:
(index.html)
Welcom to My Home Page
Hi,there.My name is Mr.Ricardo, and this is my home page. Here are some of my interests:
Shouting
Sleeping
Eating
<html>
<head>
<title>Home Page</title>
</head>
<body>
<h1>Welcom to My Home Page</h1>
<p>Hi,there.My name is Mr.Ricardo, and this is my home page. Here are some of my interests:</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>
</body>
</html>
以上是关于XML快速写网页-02的主要内容,如果未能解决你的问题,请参考以下文章
巧用Vscode编辑器,快速编辑代码,教你一键写完一段代码,向合格的cv工程师前进