XPathExpression.mjs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /**
  2. * @author Mikescher (https://github.com/Mikescher | https://mikescher.com)
  3. * @copyright Crown Copyright 2016
  4. * @license Apache-2.0
  5. */
  6. import Operation from "../Operation";
  7. import OperationError from "../errors/OperationError";
  8. import xmldom from "xmldom";
  9. import xpath from "xpath";
  10. /**
  11. * XPath expression operation
  12. */
  13. class XPathExpression extends Operation {
  14. /**
  15. * XPathExpression constructor
  16. */
  17. constructor() {
  18. super();
  19. this.name = "XPath expression";
  20. this.module = "Code";
  21. this.description = "Extract information from an XML document with an XPath query";
  22. this.infoURL = "https://wikipedia.org/wiki/XPath";
  23. this.inputType = "string";
  24. this.outputType = "string";
  25. this.args = [
  26. {
  27. "name": "XPath",
  28. "type": "string",
  29. "value": ""
  30. },
  31. {
  32. "name": "Result delimiter",
  33. "type": "binaryShortString",
  34. "value": "\\n"
  35. }
  36. ];
  37. }
  38. /**
  39. * @param {string} input
  40. * @param {Object[]} args
  41. * @returns {string}
  42. */
  43. run(input, args) {
  44. const [query, delimiter] = args;
  45. let doc;
  46. try {
  47. doc = new xmldom.DOMParser().parseFromString(input, "application/xml");
  48. } catch (err) {
  49. throw new OperationError("Invalid input XML.");
  50. }
  51. let nodes;
  52. try {
  53. nodes = xpath.parse(query).select({ node: doc, allowAnyNamespaceForNoPrefix: true });
  54. } catch (err) {
  55. throw new OperationError(`Invalid XPath. Details:\n${err.message}.`);
  56. }
  57. const nodeToString = function(node) {
  58. return node.toString();
  59. };
  60. return nodes.map(nodeToString).join(delimiter);
  61. }
  62. }
  63. export default XPathExpression;