xpath2.js icon indicating copy to clipboard operation
xpath2.js copied to clipboard

Use a custom function in xpath

Open alexgoaga opened this issue 2 years ago • 1 comments

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.

alexgoaga avatar Sep 12 '22 18:09 alexgoaga

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

drakesolutions avatar Jan 31 '23 17:01 drakesolutions