0

I have a java objects tree structure (model) created using java Lists and Maps, and I want to evaluate an xpath of the following sort:

name[/type='theType']

This xpath expression needs both the context node and the root node. However, I've found no way how to pass both nodes to JXPath for evaluation. I've tried several variants of the following code (tried to exchange root and context, null instead of rootContext etc.):

JXPathContext rootContext = JXPathContext.newContext(rootNode);
JXPathContext contextContext = JXPathContext.newContext(rootContext, contextNode);
Pointer p = contextContext.getPointer(xpath);
return p.getNode();

but none worked. In contrast to a XML DOM model, in containers you have no direct access from a context node to the root node.

Would you have any advice on how to do that?

1 Answer 1

1

Until someone suggests a direct solution, I've resolved the problem this way:

I created a Variables resolver for variable "__root" and set it to the jxpath context like this:

xpathContext.setVariables(new JXPathVariablesResolver(...));

Then I find all root references in the xpath and replace them with "$__root/":

String xpFixed = fixAbsoluteXPaths(xp);
Pointer p = xpathContext.getPointer(xpFixed);

Here is the used function:

public static final Pattern reAbsInnerXPath = Pattern.compile(
        "(^|[\\(\\[\\|,])\\s*/"); //TODO: avoid matches inside strings

protected String fixAbsoluteXPaths(String xpath) {
    Matcher m = reAbsInnerXPath.matcher(xpath);
    return m.replaceAll("$1\\$__root/");
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.