功能就是题目所述,我的python2.7,装在windows环境,我使用的开发工具是wingide 6.0
1、首先是我设计的简单的一个xml文件,也就是用来解析的源文件
下面是这个文件website.xml内容:
<website><page name="index" title="fuckyou"> <h1>welcome to</h1> <p>this is a moment</p><ul><li><a href="shouting.html" rel="external nofollow" >Shouting</a></li></ul></page><page name="shouting" title="mother"><h1>My name is likeyou</h1></page></website>
解释:page就是对应一个html文件,这里有两个page也就是要解析成两个html文件,然后分别是index.html和shouting.html,其中在index.html中通过<a>链接转到shouting.html文件中显示shouting.html文件的内容
2、python代码实现解析(xmltest.py)
#!D:/Python27/python.exe#-*- coding:utf-8 -*-from xml.sax import parsefrom xml.sax.handler import ContentHandlerclass PageCreate(ContentHandler): pagethrough = False def startElement(self, name, attrs): if name == 'page': self.pagethrough = True self.out = open(attrs['name'] + '.html', 'w') self.out.write('<html>/n<head>/n') self.out.write('<title>%s</title>/n' %(attrs['title'])) self.out.write('</head>/n<body>/n') elif self.pagethrough: self.out.write('<') self.out.write(name) for str,val in attrs.items(): self.out.write(' %s="%s"' %(str, val)) self.out.write('>') def endElement(self, name): if name == 'page': self.out.write('</body>/n</html>') self.pagethrough = False self.out.close() if self.pagethrough: self.out.write('<') self.out.write('/' + name) self.out.write('>') def characters(self, content): if self.pagethrough: self.out.write(content) parse('D://pyproject//file//website.xml', PageCreate())
代码解释:
使用xml.sax解析方法调用parse方法来解析,自己创建了一个解析类,继承了ContentHandler,在里面分别重写了startelement和endelement方法还有charactors方法,startelement方法是当找到xml文件中的开头标签时调用,如<a>、<h1>,passthrough变量是为了判断当前是否在page标签里面,true表示在page标签里面,就是属于当前page页面的元素,因为xml.sax是关注标签的,他不会管你是否在当前哪个page里面,然后后面的代码都容易理解,就是添加html的开头标签<html><head><body>等,注意,attrs储存的是标签的属性,例如<page>里面name="shouting",name="index",那么就attrs就储存这name="shouting"这个东西,从而在attrs里面获取name属性里面的shouting和index作为html文件的文件名,同理<a>里面的href=……也是通过这个数据获取,分别存在str和val变量中,并且通过write写进文件。
新闻热点
疑难解答