2018-05-27 23:07:09 +02:00
|
|
|
/**
|
|
|
|
* @author Mikescher (https://github.com/Mikescher | https://mikescher.com)
|
|
|
|
* @copyright Crown Copyright 2016
|
|
|
|
* @license Apache-2.0
|
|
|
|
*/
|
|
|
|
|
|
|
|
import Operation from "../Operation";
|
|
|
|
import OperationError from "../errors/OperationError";
|
2018-05-29 00:42:43 +02:00
|
|
|
import xmldom from "xmldom";
|
|
|
|
import xpath from "xpath";
|
2018-05-27 23:07:09 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* XPath expression operation
|
|
|
|
*/
|
|
|
|
class XPathExpression extends Operation {
|
|
|
|
|
|
|
|
/**
|
|
|
|
* XPathExpression constructor
|
|
|
|
*/
|
|
|
|
constructor() {
|
|
|
|
super();
|
|
|
|
|
|
|
|
this.name = "XPath expression";
|
|
|
|
this.module = "Code";
|
|
|
|
this.description = "Extract information from an XML document with an XPath query";
|
2018-08-21 20:07:13 +02:00
|
|
|
this.infoURL = "https://wikipedia.org/wiki/XPath";
|
2018-05-27 23:07:09 +02:00
|
|
|
this.inputType = "string";
|
|
|
|
this.outputType = "string";
|
|
|
|
this.args = [
|
|
|
|
{
|
|
|
|
"name": "XPath",
|
|
|
|
"type": "string",
|
|
|
|
"value": ""
|
|
|
|
},
|
|
|
|
{
|
|
|
|
"name": "Result delimiter",
|
|
|
|
"type": "binaryShortString",
|
|
|
|
"value": "\\n"
|
|
|
|
}
|
|
|
|
];
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param {string} input
|
|
|
|
* @param {Object[]} args
|
|
|
|
* @returns {string}
|
|
|
|
*/
|
|
|
|
run(input, args) {
|
|
|
|
const [query, delimiter] = args;
|
|
|
|
|
|
|
|
let doc;
|
|
|
|
try {
|
2018-05-29 00:42:43 +02:00
|
|
|
doc = new xmldom.DOMParser().parseFromString(input, "application/xml");
|
2018-05-27 23:07:09 +02:00
|
|
|
} catch (err) {
|
|
|
|
throw new OperationError("Invalid input XML.");
|
|
|
|
}
|
|
|
|
|
|
|
|
let nodes;
|
|
|
|
try {
|
|
|
|
nodes = xpath.select(query, doc);
|
|
|
|
} catch (err) {
|
|
|
|
throw new OperationError(`Invalid XPath. Details:\n${err.message}.`);
|
|
|
|
}
|
|
|
|
|
|
|
|
const nodeToString = function(node) {
|
|
|
|
return node.toString();
|
|
|
|
};
|
|
|
|
|
|
|
|
return nodes.map(nodeToString).join(delimiter);
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
export default XPathExpression;
|