简体   繁体   中英

Transform XML String [not file!] with XSLT String in Node.js to HTML

I have two strings.

The first one is a xml string, saved as a string, not from a file. The second one is a string I load from a XSLT file with fs.readFile(...) .

I already tried using libxslt but can't install it via npm due to some errors about MSBuildTools and so on.

Are there any alternatives for libxslt ? I already came across xslt-processor too, but it only accepts files as parameters.

EDIT 1:

to provide you an overview, the XSLT file and an example XML file (both handled as strings in the app) can be downloaded here:

I somehow got a workaround for my problem:

  1. I now use the xth library (install via npm: npm i xth )
  2. import it into my function: var xth = require('xth');
  3. put the xml String into a data URI: var xml = 'data:text/xml,' + encodeURIComponent(xmlString);
  4. the XSLT file is now not a String but the file: var xsl = './../components/ELGA_Stylesheet_v1-0.xsl';
  5. Then, I just call the method xth as in the example at xth - npm

    1 xth(xml, xsl, function (html) { 2 html = html.replace(/&lt;/g, "<"); 3 html = html.replace(/&gt;/g, ">"); 4 html = html.replace(/&amp;/g, "&"); 5 openWindow(html); 6 });

  6. the item html is the xslt transformed string, I had one final problem: in the <script> Tags of the output string, the symbols <,> and & were there as &amplt;, &ampgt;, and &ampamp; which caused problems. lines 2 to 4 are the workaround for this issue

openWindow(html) is my own method to open the result string in a new electron window.

NOTE: one problem remains: as mentioned here , navigation via # in <a href=#id> doesn't work, because Chromium doesn't allow navigation to top frame to data uri.

Disclaimer: not tested for the attached XML/XSLT.

You could use saxon-js :

const saxon = require("saxon-js");
const env = saxon.getPlatform();

const doc = env.parseXmlFromString(yourStringXSLT);
// monkey-patch to avoid a "Required cardinality of value of parameter $static-base-uri is exactly one; supplied value is empty" compile error
doc._saxonBaseUri = "file:///";

const sef = saxon.compile(doc);
// you can save and reuse the SEF for future transforms, if applicable

const resultStringXML = saxon.transform({
  stylesheetInternal: sef,
  sourceText: yourStringXML
});

This approach may not be perfect (esp. the _saxonBaseUri hack) - but I couldn't find anything better (for saxon-js ) documented online (except for the xslt3 command-line based approach).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM