I have xsl
file I would like to apply to some XML content in node.js
. I found saxon-js
and it seems to offer what I need. While I'm slightly lost in the documentation, it seems like I should first convert my xsl
file to .sef
file before running transform in node.
saxon-js
readme mentiones other package, xslt3
that should be able to do that (see readme):
Compiling a stylesheet
To compile a stylesheet held in books.xsl to a SEF file in books.sef.json, to be run either in the browser or Node.js, use the command line:
xslt3 -xsl:books.xsl -export:books.sef.json -t -ns:##html5
However, after installing xslt3
package, there's no executable available to run the conversion.
Am I missing something? How can I convert xsl
to sef.json
(one time is OK, don't need to run it from server dynamically or anything)?
FWIW, here's how you can do this programmatically, without xslt3
(in case someone else lands here, looking for a code-based solution):
// xsl: path to XSLT file
// xml: path to XML file to be transformed
const saxon = require("saxon-js");
const env = saxon.getPlatform();
const doc = env.parseXmlFromString(env.readFile(xsl));
// hack: avoid error "Required cardinality of value of parameter $static-base-uri is exactly one; supplied value is empty"
doc._saxonBaseUri = "file:///";
const sef = saxon.compile(doc);
/* now you can use `sef`:
const resultStringXML = saxon.transform({
stylesheetInternal: sef,
sourceText: env.readFile(xml)
});
*/
This is somewhat of a monkey-patch (esp. the _saxonBaseUri
part); adding it here anyway, as I couldn't (yet) find a better/formal approach in any documentation - Saxonica or otherwise.
You can either find the executable in ./node_modules/xslt3/xslt3.js after installing the package as a local dependency in your project
npm i xslt3
❯ ./node_modules/xslt3/xslt3.js
Saxon requires a stylesheet as -xsl: argument
Error FORG0001
Cannot locate stylesheet ('/Users/<username>/Projects/saxonjs-poc/undefined')
or you can use the -g flag with npm to install xslt3 globally. Then xslt3 will be available as an executable anywhere on your machine
npm i -g xslt3
❯ xslt3
Saxon requires a stylesheet as -xsl: argument
Error FORG0001
Cannot locate stylesheet ('/Users/<username>/Projects/saxonjs-poc/undefined')
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