How to transform an XML file using XSLT in Python?
Question:
Good day! Need to convert xml using xslt in Python. I have a sample code in php.
How to implement this in Python or where to find something similar? Thank you!
$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);
Answers:
LXML is a widely used high performance library for XML processing in python based on libxml2 and libxslt – it includes facilities for XSLT as well.
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))
The best way is to do it using lxml, but it only support 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 options from Use saxon with python
Good day! Need to convert xml using xslt in Python. I have a sample code in php.
How to implement this in Python or where to find something similar? Thank you!
$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);
LXML is a widely used high performance library for XML processing in python based on libxml2 and libxslt – it includes facilities for XSLT as well.
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))
The best way is to do it using lxml, but it only support 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 options from Use saxon with python