功能就是題目所述,我的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寫進文件。
新聞熱點
疑難解答