有人知道如何在 ECMA Script(datapower) 中使用 xpath 表达式访问 XML 数据吗?
IBM 信息中心没有关于如何访问 XML 数据的信息
如果您有任何用于访问 XML 数据的示例脚本,请提供
谢谢
最佳答案
GatewayScript 不支持 ECMA (Node.js) 实现中的任何 XML Dom。 然而,我已经成功地使用了模块 XPATH 和 DOM。 下载 XMLDom ( https://github.com/jindw/xmldom ) 和 Xpath ( https://github.com/goto100/xpath ) Node.js 模块并将以下脚本添加到您的 DP 目录:
- dom-parser.js
- dom.js
- sax.js
- xpath.js
要在 DataPower GWS 中使用它,您首先需要从 INPUT 获取 XML 数据:
// 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
}
}
这应该是一个工作示例...如果移动模块,则需要更改模块的路径。 我在 store:///中有一个目录,我可以在其中添加我的 GWS 模块。
希望你能让它飞起来!
关于javascript - Datapower 中的 ECMA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26582051/