Use python to convert XML and XSL to HTML

Source: Internet
Author: User
Tags xsl

A small program that used python to process XML Conversion the other day to convert XML and XSL to HTML.

Libxml2 is used. Therefore, libxml2 must be installed first.

#-*-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, pai_file_name ):
Self. _ xml = libxml2.parsefile (xml_file_name)
If self. _ xml = none:
Return 0
Styledoc = libxml2.parsefile (pai_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 ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.