-1

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] 
loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
Narendran
  • 1
  • 1
  • 3

2 Answers2

1

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);   
loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
  • Thanks Loganfsmyth, I tried the same, but it does not return any results. I used with some sample xml and xsl – Narendran Dec 16 '14 at 17:05
  • Execution does not go beyond the line "var stylesheetObj = libxmljs.parseXml(stylesheetSource);" – Narendran Dec 16 '14 at 17:12
  • sorry, it did not pass this line var stylesheet = libxslt.parse(stylesheetObj); – Narendran Dec 16 '14 at 17:41
  • `did not pass` is not a useful description. Was there an error message? – loganfsmyth Dec 16 '14 at 17:45
  • No there was no error logged in NodeJs error file, but it stops the server listening in the port. I used res.end() to find where it was stopping the execution and it was not going beyond the line var stylesheet = libxslt.parse(stylesheetObj); – Narendran Dec 16 '14 at 17:59
  • Any suggestion on the same? – Narendran Dec 24 '14 at 00:35
  • just use var stylesheet = libxslt.parse(stylesheetSource); instead of var stylesheet = libxslt.parse(stylesheetObj); @Narendran – Ramesh May 05 '15 at 17:03
0

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);
}); 
Fuad
  • 1