ilinsky / xpath2.js

xpath.js - Open source XPath 2.0 implementation in JavaScript (DOM agnostic)
MIT License
80 stars 12 forks source link

Use a custom function in xpath #16

Open alexgoaga opened 2 years ago

alexgoaga commented 2 years ago

Hi,

I would like to use a custom function in xpath, but I don't see any clear documentation on how to do that.

Let's say that I want to use a custom match for regular expressions. How can I write one?

I looked at StaticContext, but it is not clear for me.

Thanks, Alex.

drakesolutions commented 1 year ago

I have prepared very small example with one custom user function called "factorialize":

    const staticContext = xpath.createStaticContext();

    staticContext.signatures    = {};
    var cXSDecimal = require('xpath2.js/lib/types/schema/simple/atomic/XSDecimal');

   // add our custom function to staticContext
    staticContext.functions["factorialize"] = (oValue) =>{

        var num = global.Math.round(oValue[0].textContent);    
        var result = num;
        if (num === 0 || num === 1) 
          return 1; 
        while (num > 1) { 
          num--;
          result *= num;
        }

        return new cXSDecimal(result);
    };

    // add parameters to this function
    staticContext.signatures["factorialize"]    =  [[cXSDecimal, '?']];

    const parser = new DOMParser();
    const document = parser.parseFromString('<data ><some>5</some></data>', "application/xml");

    let result = xpath.evaluate ("factorialize(data/some)",document ,staticContext);
    console.log(result[0]);  // output to console is 120