How to convert xml file using XSLT in Python?

Good afternoon! Need to convert xml using xslt to Python. I have some sample code in php.

How to implement this in Python or where to find something similar? Thank!

$xmlFileName = dirname(__FILE__)."example.fb2"; $xml = new DOMDocument(); $xml->load($xmlFileName); $xslFileName = dirname(__FILE__)."example.xsl"; $xsl = new DOMDocument; $xsl->load($xslFileName); // Configure the transformer $proc = new XSLTProcessor(); $proc->importStyleSheet($xsl); // attach the xsl rules echo $proc->transformToXML($xml); 
+57
python xml xslt converter
May 22 '13 at 18:17
source share
3 answers

Using lxml ,

 import lxml.etree as ET dom = ET.parse(xml_filename) xslt = ET.parse(xsl_filename) transform = ET.XSLT(xslt) newdom = transform(dom) print(ET.tostring(newdom, pretty_print=True)) 
+94
May 22 '13 at 18:23
source share

LXML is a widely used high-performance library for XML processing in python, based on libxml2 and libxslt - it also includes tools for XSLT .

+5
May 22 '13 at 18:22
source share

The best way is to use lxml, but it only supports XSLT 1

 import os import lxml.etree as ET inputpath = "D:\\temp\\" xsltfile = "D:\\temp\\test.xsl" outpath = "D:\\output" for dirpath, dirnames, filenames in os.walk(inputpath): for filename in filenames: if filename.endswith(('.xml', '.txt')): dom = ET.parse(inputpath + filename) xslt = ET.parse(xsltfile) transform = ET.XSLT(xslt) newdom = transform(dom) infile = unicode((ET.tostring(newdom, pretty_print=True))) outfile = open(outpath + "\\" + filename, 'a') outfile.write(infile) 

to use XSLT 2 you can check the parameters Use saxon with python

+1
Oct 17 '17 at 10:27
source share



All Articles