Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use a custom function in xpath #16

Open
alexgoaga opened this issue Sep 12, 2022 · 1 comment
Open

Use a custom function in xpath #16

alexgoaga opened this issue Sep 12, 2022 · 1 comment

Comments

@alexgoaga
Copy link

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
Copy link
Collaborator

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants