XSL Transforms in JavaScript - Dave's Blog

Search
My timeline on Mastodon

XSL Transforms in JavaScript

2007 Oct 7, 4:12In a previous post I mentioned an xsltproc like js file I made. As noted in that post, on Windows you can write console script files in JavaScript, name them foo.js, and execute them from the command prompt. I later found that MSDN has an XSLT javascript sample which looks similar to mine, but I like mine better for the XSLT parameter support and having a non-ridiculous way of interpreting filenames. The code for my xsltproc.js follows. The script is very simple and demonstrates the ease with which you can manipulate these system objects and all it takes is opening up notepad.
var createNewXMLObj = function() {
   var result = new ActiveXObject("MSXML2.FreeThreadedDOMDocument");
   result.validateOnParse = false;
   result.async = false;
   return result;
}

var args = WScript.arguments;
var ofs = WScript.CreateObject("Scripting.FileSystemObject");

var xslParams = [];
var xmlStyle = null;
var xmlInput = null;
var inputFile = null;
var outputFile = null;
var error = false;

for (var idx = 0; idx < args.length && !error; ++idx)
   if (args.item(idx) == "-o") {
      if (idx + 1 < args.length) {
         outputFile = ofs.GetAbsolutePathName(args.item(idx + 1));
         ++idx;
      }
      else
         error = true;
   }
   else if (args.item(idx) == "--param" || args.item(idx) == "-param") {
      if (idx + 2 < args.length) {
         xslParams[args.item(idx + 1)] = args.item(idx + 2);
         idx += 2;
      }
      else
         error = true;
   }
   else if (xmlStyle == null) {
      xmlStyle = createNewXMLObj();
      xmlStyle.load(ofs.GetAbsolutePathName(args.item(idx)));
   }
   else if (xmlInput == null) {
      inputFile = ofs.GetAbsolutePathName(args.item(idx));
      xmlInput = createNewXMLObj();
      xmlInput.load(inputFile);
   }

if (xmlStyle == null || xmlInput == null || error) {
   WScript.Echo('Usage:\n\t"xsltproc" xsl-stylesheet input-file\n\t\t["-o" output-file] *["--param" name value]');
}
else {
   var xslt = new ActiveXObject("MSXML2.XSLTemplate.3.0");
   xslt.stylesheet = xmlStyle;
   var xslProc = xslt.createProcessor();
   xslProc.input = xmlInput;

   for (var keyVar in xslParams)
      xslProc.addParameter(keyVar, xslParams[keyVar]);

   xslProc.transform();

   if (outputFile == null)
      WScript.Echo(xslProc.output);
   else {
      var xmlOutput = createNewXMLObj();
      xmlOutput.loadXML(xslProc.output);
      xmlOutput.save(outputFile);
   }
}
PermalinkCommentsjs xml jscript windows xslt technical xsltproc wscript xsl javascript
Older Entries Creative Commons License Some rights reserved.