本文实例讲述了python将xml和xsl转换为html的方法。分享给大家供大家参考。具体分析如下:
这里需要用libxml2,所以还要先安装了libxml2模块才能使用。代码如下:
# -*- coding: mbcs -*-#!/usr/bin/pythonimport libxml2, libxsltclass 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 = noneif __name__ == '__main__': test = compoundxml() test.do('test/testxmlutil.xml', 'test/testxmlutil.xsl') print test.get_translated() test.save_translated('test/testxmlutil.htm') test.release()
希望本文所述对大家的python程序设计有所帮助。