欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python将xml xsl文件生成html文件存储示例讲解

程序员文章站 2023-11-08 07:59:33
前提:安装libxml2 libxstl 官方网站:http://xmlsoft.org/xslt/index.html 安装包下载:http://xmlsoft.or...

前提:安装libxml2 libxstl

官方网站:http://xmlsoft.org/xslt/index.html

安装包下载:http://xmlsoft.org/sources/

下面是windows平台的exe安装文件下载:

http://xmlsoft.org/sources/win32/python/
这是转载的测试代码:

复制代码 代码如下:

# -*- coding: mbcs -*-
#!/usr/bin/python

import libxml2, libxslt


class compoundxml:
    def __init__(self):
        self._result = none
        self._xsl = none
        self._xml = none

      
    def do(self, xml_file_name, xsl_file_name):      
        self._xml = libxml2.parsefile(xml_file_name)
        if self._xml == none:
            return 0
        styledoc = libxml2.parsefile(xsl_file_name)
        if styledoc == none:
            return 0
        self._xsl = libxslt.parsestylesheetdoc(styledoc)
        if self._xsl == none:
            return 0

        self._result = self._xsl.applystylesheet(self._xml, none)              

    def get_xml_doc(self):
        return self._result          

    def get_translated(self):
        return self._result.serialize('utf-8')      

    def save_translated(self, file_name):
        self._xsl.saveresulttofilename(file_name, self._result, 0)

    def release(self):
        '''
        this function must be called in the end.
        '''
        self._xsl.freestylesheet()
        self._xml.freedoc()
        self._result.freedoc()
        self._xsl = none
        self._xml = none
        self._result = none

if __name__ == '__main__':
    test = compoundxml()
    test.do('test/testxmlutil.xml', 'test/testxmlutil.xsl')
    print test.get_translated()
    test.save_translated('test/testxmlutil.htm')
    test.release()