XSL Transformation With Parameters

Audience Level

Intermediate to advanced

Summary

A JScript function to load an XML file, load an XSL file, add dynamically created parameters to the XSL stylesheet and then return the string result of the XSLT transformation. Input parameter may either be single “paramName” and “paramValue” strings or arrays of “paramName”s and “paramValue”s.

If arrays are used then both arrays must be the same length with a 1-to-1 relationship between a parameter name in the “paramName” array and its value in the “paramValue” array.

Source Code

/*
Function: doTransformXMLWithAddParam()
Description:
Returns:
History:
20050131 1602GMT    v1      Andrew Urquhart     Comment added
*/

function doTransformXMLWithAddParam(xmlFilePath, xslFilePath, paramName, paramValue) {
    try {
        var xslt    = new ActiveXObject("MSXML2.XSLTemplate.4.0");
        var xmlObj  = new ActiveXObject("MSXML2.DOMDocument.4.0");
        xmlObj.async = false;
        xmlObj.resolveExternals = false;
        var xmlDoc = xmlObj.load(xmlFilePath);
        if (!xmlDoc) {
            throw new Error(1, "Unable to load XML file \"" + xmlFilePath + "\"");
        }
        if (xmlObj.parseError.errorCode != 0) {
            throw new Error(2, "\"" + xmlObj.parseError.reason + "\", line=" + xmlObj.parseError.line);
        }
        else {
            // Load style sheet.
            var xslObj = new ActiveXObject("MSXML2.FreeThreadedDOMDocument.4.0");
            xslObj.async = false
            xslObj.resolveExternals = false;
            xslObj.load(xslFilePath);
            xslt.stylesheet = xslObj;
            if (!xslObj) {
                throw new Error(3, "Unable to load XSL file \"" + xslFilePath + "\"");
            }
            if (xslObj.parseError.errorCode != 0) {
                throw new Error(4, "\"" + xslObj.parseError.reason + "\", line=" + xslObj.parseError.line);
            }
            else {
                // Add parameter to XSL sheet
                var xslProc = xslt.createProcessor();
                xslProc.input = xmlObj;
                if (typeof paramName == "string") {
                    // STRING PARAMETERS USED
                    xslProc.addParameter(paramName, paramValue);
                }
                else if (typeof paramName == "object") {
                    // ARRAY PARAMETERS USED
                    for (var i in paramName) {
                        xslProc.addParameter(paramName[i], paramValue[i]);
                    }
                }
                xslProc.transform();
                return(xslProc.output);
            }
        }
    }
    catch (err) {
        propError(err, arguments);
    }
}

Download

Download the source directly.

Advertisement

Feedback

Voting Panel
Is this useful?
or
Did you find any bugs?
or
Did it solve your programming problem?
or
Rate this script: (0=poor, 5=very good)
Answers are anonymous, only the combined totals are stored. Uses cookies.