使用python將xml檔案解析成html檔案

2021-08-11 15:18:38 字數 1809 閱讀 3439

功能就是題目所述,我的python2.7,裝在windows環境,我使用的開發工具是wingide 6.0

1首先是我設計的簡單的乙個xml檔案,也就是用來解析的原始檔

下面是這個檔案website.xml內容:

this is a moment

解釋:page就是對應乙個html檔案,這裡有兩個page也就是要解析成兩個html檔案,然後分別是index.html和shouting.html,其中在index.html中通過鏈結轉到shouting.html檔案中顯示shouting.html檔案的內容

2python**實現解析(xmltest.py)

#!d:\python27\python.exe

#-*- coding:utf-8 -*-

from xml.sax import parse

from xml.sax.handler import contenthandler

class 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('\n\n\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('\n')

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檔案中的開頭標籤時呼叫,如、這類的結尾標籤的時候呼叫,新增結尾的標籤,如果是檔案結尾,那麼就是,這時候就把、這些html的結尾標籤新增進去,否則,就是page頁面裡面的元素結尾標籤

characters就是將開頭標籤於結尾標籤之間找到的字串新增進去

最後我們把python**執行起來之後就可以看到在同一目錄下生成了兩個html檔案,分別是shouting.html和index.html,開啟index.html就可以看到乙個叫做「shouting」的鏈結,點過去就開啟了shouting.html

使用Python讀寫XML檔案

from xml.etree.elementtree import elementtree from xml.etree.elementtree import element from xml.etree.elementtree import subelement from xml.etree.el...

將XML檔案寫入文件

public static void main string args throws exception 建立乙個空的document物件 document doc documenthelper.createdocument 建立乙個根元素 element stus doc.addelement s...

通過python將xml檔案轉換成html檔案

def main maxwidth 100 用於規範字段的長度 print start count 0 while true try line input if count 0 color lightgreen elif count 2 取餘 color white else color light...