Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transform an XML file using XSLT in 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); 
like image 999
aphex Avatar asked May 22 '13 18:05

aphex


People also ask

How does XSLT transform 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.

Can XSLT transform XML to CSV?

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.

Can XSLT transform XML to JSON?

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.


2 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)) 
like image 149
unutbu Avatar answered Sep 26 '22 05:09

unutbu


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.

like image 23
miku Avatar answered Sep 25 '22 05:09

miku