transform module

The transform provides methods to access and manipulate the data in an XML document.

The transform module has XPath query and XSLT functions. Access this module with the require('transform') statement.

transform.xpath()

Select nodes from an XML document by using an XPath expression.

Syntax
transform.xpath(expression,xmldom,function(error,nodelist){})
transform.xpath(options,function(error,nodelist){})
Parameters
expression
The XPath expression to evaluate.
xmldom
The Node or NodeList object to apply the XPath expression to.
options
A JSON object that contains up to three properties: expression, xmldom, and namespace.
error
The error parameter that contains error details when an error occurs.
nodelist
The evaluated NodeList object.
Guidelines
The transform.xpath() method queries an XML Node or NodeList with an XPath expression. The result is an XML NodeList that can contain zero or more Node objects.

The method signatures provide different mechanisms to supply the XPath expression and the XML to query. You can either specify them as arguments to the function or in a JSON options argument that contains properties for these values. The JSON options object defines the XPath query options.

expression
The XPath expression to evaluate.
xmldom
The XML DOM object that the XPath expression is applied to.
namespace
The JSON object that specifies the corresponding namespace URI for every namespace prefix that the XPath expression uses. The structure of the namespace object shows a list of named properties. The property name is the prefix and the value is the namespace URI.
'namespace': { 'ns1': 'http://abc.com/books',
               'ns2': "http://abc/com/movies'}

To have namespace bindings in the transform.xpath() expression, use the options syntax.

Example
This example demonstrates how to select book elements from a created XML document by using the XPath method. The XPath expression is qualified by the namespace prefix ns1 that is bound to http://publisher.com/books with the namespace option. After the evaluation is complete, the result is returned in the xmlNodeList and written to the output context.
var transform = require('transform');
var doc = XML.parse(
    '<books xmlns="http://publisher.com/books">' +
    '  <book><title>JavaScript</title><price>22.99</price></book>' +
    '  <book><title>XSLT</title><price>35</price></book>' +
    '</books>');

var options = { 'expression': '//ns1:book',
                'xmldom': doc,
                'namespace': { 'ns1': 'http://publisher.com/books' }
              };

transform.xpath(options, function(err, xmlNodeList) {
  if (err) {
    session.out.write(err);
  }
  else {
    session.output.write(xmlNodeList);
  }
});

transform.xslt()

Transform nodes in an XML document by using an XSLT stylesheet.

Syntax
transform.xslt(location,xmldom,function(error,nodelist,abortinfo){})
transform.xslt(options,function(error,nodelist,abortinfo){})
Parameters
location
The location is the stylesheet URL as a string. For example, local:///convert.xsl.
xmldom
The input data for the transformation. It can be a Node or NodeList object. If no input is needed, the value can be null or undefined.
options
A JSON object that contains up to four properties: xmldom, location, honorAbort, and parameters. Optional parameters are passed to the stylesheet program as a nodeset object. The default value is an empty nodeset.
error
The error parameter that contains error details when an error occurs. If no error occurs, the nodelist contains the transformed result in a NodeList object. In this case, the error object is null.
nodelist
The nodelist contains the transformed result as a NodeList object or null.
abortinfo
A stylesheet can receive errors or stop during run time. When a stylesheet stops during run time, the abortinfo parameter contains the termination code and message. If no error occurs, the abortinfo object is null.
Guidelines
The transform.xslt method starts an XSLT transformation against an XML Node or NodeList with the stylesheet provided. The transformed result is an XML NodeList that can contain zero or more Node objects. In addition, headers, context, and service variables that are set in the stylesheet can be retrieved in the script upon the completion of the XSLT transformation.
Sample options JSON object.
var options = {
  "xmldom": myXmlObj,
  "location": "local:///convert.xsl",
  "honorAbort": true,
  "parameters" : {"p1": "value1", "{http://www.datapower.com/param/config}p2": "value2"}
};
xmldom
The input data for the transformation. It can be a Node or NodeList object. Optional if options are used. Specifying this option as null or undefined, or providing no information for the option, is the same as providing no input data to the stylesheet.
location
The URL of the stylesheet as a string. Required if options are used. You can supply the stylesheet location and the XML to transform in either of two ways. Specify them either as arguments to the function or as a JSON options argument, which contains properties for these values.
honorAbort
Indicates whether the GatewayScript action stops when the stylesheet stops during its execution. Optional if options are used.
  • When honorAbort set true (the default), the script stops if the stylesheet does. When options are not used, the default also applies. The only way to override this default is to specify honorAbort : false in an options object.
  • When honorAbort set false, the script does not stop when a stylesheet stops. By examining the abortinfo object for the detailed termination code and message. Your own error handling can determine whether to stop the GatewayScript action (by using session.reject, for example).
parameters
The parameters option is an object that has one to many properties. Each property value is a string. The property key name can be specified in one of the following formats. Ensure that the parameters are consistent with the parameter name specification in the called XSLT stylesheet.
{namespace}localname
The full namespace URI as defined in the XSLT stylesheet. For illustrative purposes, the following snippets are the code in the GatewayScript and XSLT files.
  • The GatewayScript has "{http://www.example.com/bar}paramfoo" : "value1"
  • The XSLT has the xmlns:foo="http://www.example.com/bar" namespace declaration and the parameter as follows.
    <xsl:param name= "foo:paramfoo" select="'unset'"/>
localname
Without a full namespace URI in the GatewayScript file from the XSLT stylesheet, processing uses http://www.datapower.com/param/config as the namespace. This namespace is the default DataPower parameter namespace.
Example
  1. The example script file.
    var transform = require('transform');
    
    var xmldata = XML.parse(
        "<PO>" +
        "  <item id='x004' price='23' qty='50'/>" +
        "  <item id='x007' price='18' qty='20'/>" +
        "  <item id='x009' price='30' qty='11'/>" +
        "</PO>");
    
    // The location specifies the stylesheet and xmldom specifies the 
    // nodes /PO/item for transformation input
    var options = {
        "location": "local:///xml/xslt/calculate.xsl",
        "xmldom": xmldata.documentElement.getElementsByTagName("item")
    
    };
    transform.xslt(options, function(error, nodelist, abortinfo) {
        if (error) {
            session.output.write("An error was returned when executing '" + options.location + "'");
        }
        else {
            //write out the transformed result
            session.output.write(nodelist);
        }
    });
  2. The calculate.xsl stylesheet is started by using a transform.xslt() call.
    <?xml version="1.0" encoding="utf-8"?>
    <xsl:stylesheet version="1.0"
        xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    
      <xsl:output method="xml"/>
      <xsl:template match="/">
        <Output>
        <xsl:for-each select="/*">
          <amount><xsl:value-of select="./@price * ./@qty"/></amount>
        </xsl:for-each>
        </Output>
      </xsl:template>
    </xsl:stylesheet>
  3. The results of the XSLT run of the script return in nodelist.item(0). Applying an XML.stringify method to the result in the script yields.
    <?xml version="1.0" encoding="UTF-8"?>
    <Output><amount>1150</amount><amount>360</amount><amount>330</amount></Output>
  4. The parameters option in this example specifies two session parameters that are provided to the called stylesheet.
    var transform = require('transform');
    
    session.input.readAsXML(function(error, nodelist) {
       if (!error) {
           var options = {
                 "location": "local:///simple.xsl",
                 "xmldom": nodelist,
                 "honorAbort": true,
                 "parameters": {
                       "p1": "overwrite p1",
                       "{http://www.datapower.com/param/config}p2": "overwrite p2"
                  }
           };
           transform.xslt(options, function(error, nodelist, isAbort) {
    
                if (!error && nodelist && nodelist.length > 0) { 
    
                    session.output.write(XML.stringify({omitXmlDeclaration: true}, nodelist));
                } else {
                    session.output.write("nothing");
                }
            });
        } else { 
            console.error('readAsXML error '+error);
     
            session.output.write(error);
        }
    });