sk08
sk08

Reputation: 11

ECMA in Datapower

anybody know how to access XML data using xpath expression in ECMA Script(datapower)?

IBM infocenter doesn't have this information on how to access XML data

Please provide if you have any sample script for accessing XML data

Thanks

Upvotes: 1

Views: 3036

Answers (2)

kirill.login
kirill.login

Reputation: 951

At least from 7.0.0 firmware version Gatewayscript is able to work with XPATH and DOM easily. Snippet from the DP store:

//reading body from the rule input
session.input.readAsXML(function (error, nodeList) {
    if (error) {
    //error behaviour
  } else {
    var domTree;
    try {
      domTree = XML.parse(nodeList);
    } catch (error) {
      //error behaviour
    }

    var transform = require('transform'); //native gatewayscript module
    transform.xpath('/someNode/anotherNode/text()', domTree, function(error, result){
      if(error){
        //error behaviour
      }
      //some use of result, for example putting it to output
      session.output.write(result);
    }
  });
});

Upvotes: 2

Anders
Anders

Reputation: 3412

GatewayScript doesn't support any XML Dom in the ECMA (Node.js) implemented. I have however used the modules XPATH and DOM with great success. Download XMLDom (https://github.com/jindw/xmldom) and Xpath (https://github.com/goto100/xpath) Node.js modules and add the following scripts to your DP directory:

  • dom-parser.js
  • dom.js
  • sax.js
  • xpath.js

To use it in DataPower GWS you first need to get the XML data from INPUT:

// This is where we start, grab the INPUT as a buffer
session.input.readAsBuffers(function(readAsBuffersError, data) {


    if (readAsBuffersError) {
        console.error('Error on readAsBuffers: ' + readAsBuffersError);
        session.reject('Error on readAsBuffers: ' + readAsBuffersError);
    } else {

        if (data.slice(0,5).toString() === '<?xml') {

            console.log('It is XML!');
            parseXML(data);

        }
    } //end read as buffers error
}); //end read as buffer function

function parseXML(xml) {
    // Load XML Dom and XPath modules
    var select = require('local:///xpath.js');
    var dom = require('local:///dom-parser.js');

    var doc = new dom.DOMParser().parseFromString(xml.toString(), 'text/xml');
    // Get attribute
    var nodes = select(doc, "//root/element1/@protocol");
    try {
        var val = nodes[0].value.toString();
        console.log('found xml attribute as ['+val+']');
    } catch(e) {
        // throw error here
    }

    // Get an element
    nodes = select(doc, "//root/element1/child1");
    try {
        var val = nodes[0].firstChild.data;
        console.log('elemnt found as ['+val+']');
    } catch(e) {
        //throw error here
    }

}

That should be a working sample... You need to change the path for the modules if you move them. I have a directory in store:/// where I add my GWS modules.

Hope you'll get it to fly!

Upvotes: 3

Related Questions