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);
The standard way to transform XML data into other formats is by Extensible Stylesheet Language Transformations (XSLT). You can use the built-in XSLTRANSFORM function to convert XML documents into HTML, plain text, or different XML schemas. XSLT uses stylesheets to convert XML into other data formats.
The following XSL Style Sheet (compatible with XSLT 1.0) can be used to transform the XML into CSV. It is quite generic and can easily be configured to handle different xml elements by changing the list of fields defined ar the beginning.
XSLTJSON: Transforming XML to JSON using XSLTXSLTJSON is an XSLT 2.0 stylesheet to transform arbitrary XML to JavaScript Object Notation (JSON). JSON is a lightweight data-interchange format based on a subset of the JavaScript language, and often offered as an alternative to XML in—for example—web services.
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))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With