首页 > 编程 > Python > 正文

利用python将xml文件解析成html文件的实现方法

2019-11-25 15:29:02
字体:
来源:转载
供稿:网友

功能就是题目所述,我的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写进文件。

然后endelement就是当解析到</h1>这类的结尾标签的时候调用,添加结尾的标签,如果是文件结尾,那么就是</page>,这时候就把</html>、</body>这些html的结尾标签添加进去,否则,就是page页面里面的元素结尾标签

characters就是将开头标签于结尾标签之间找到的字符串添加进去

最后我们把python代码运行起来之后就可以看到在同一目录下生成了两个html文件,分别是shouting.html和index.html,打开index.html就可以看到一个叫做“shouting”的链接,点过去就打开了shouting.html

以上这篇利用python将xml文件解析成html文件的实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表