How to transform an XML file using XSLT in Python?

aphex picture aphex · May 22, 2013 · Viewed 69.9k times · Source

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);

Answer

unutbu picture unutbu · May 22, 2013

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))