Converting XML to HTML in NodeJs using LibXSLT(throws has no method 'apply' error)

4.9k views Asked by At

Anybody worked on XML to HTML transform in Nodejs, Iam getting "has no method 'apply'"error

var fs = require('fs');   
var libxslt = require('libxslt');   
var libxmljs = require('libxmljs');   


var docSource = fs.readFileSync('Hello.xml', 'utf8');    
var stylesheetSource = fs.readFileSync('Hello.xsl', 'utf8');    
var stylesheet = libxmljs.parseXml(stylesheetSource);    
var result = stylesheet.apply(docSource);    
res.end(result);    

Error:

TypeError: Object <?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
 <xsl:template match="/hello-world"><HTML><HEAD><TITLE/></HEAD><BODY><H1><xsl:value-of select="greeting"/></H1>hello</BODY></HTML> </xsl:template>
</xsl:stylesheet>
has no method 'apply'
   at C:\WEBROOT\DM\wwwRoot\hello\node_modules\Simple_Server.js:151:42
   at Layer.handle [as handle_request] 
2

There are 2 answers

0
Fuad On

This syntax worked for me:

stylesheet.apply(doc,  function(err, result){   
console.log("result:",
    result.toString().replace(/^<\?xml version="1\.0" encoding="UTF-8"\?>\s+/, "")
    );
console.log("err:",err);
}); 
7
loganfsmyth On

The error you means your stylesheet.apply(docSource) failed because stylesheet doesn't have that method. Looking at the docs for xslt makes it pretty clear that .apply is on the results of libxslt.parse, not the result of libxmljs.parseXml. So you need to do:

var fs = require('fs');   
var libxslt = require('libxslt');   
var libxmljs = require('libxmljs');   

var docSource = fs.readFileSync('Hello.xml', 'utf8');    
var stylesheetSource = fs.readFileSync('Hello.xsl', 'utf8');  

var stylesheetObj = libxmljs.parseXml(stylesheetSource);
var doc = libxmljs.parseXml(docSource);

var stylesheet = libxslt.parse(stylesheetObj);
var result = stylesheet.apply(doc);    
res.end(result);