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?

xarx
  • 627
  • 1
  • 11
  • 27

1 Answers1

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/");
}
xarx
  • 627
  • 1
  • 11
  • 27