0

I'm using apache JXPath library to parse an XML. I'm trying to find an API in JXPath which does similar function as XPath evaluate, i.e. check if the xpath expression exists ? Its similar in the lines of

<xsl:when test="

when using xslt. Using XPath I can similarly do

XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
InputSource source = new InputSource(new StringReader(xml));
status = xpath.evaluate("/resp/status/solution", source);

If solution is not present, then it'll return status as null. Now,while using JXPath, I'm unable to figure an API in similar lines. Here's my sample code

DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();

DocumentBuilder bld = dbfactory.newDocumentBuilder();

Document metaDoc = bld.parse(in);

JXPathContext metaCtx = JXPathContext.newContext(metaDoc);

Node node = (Node)metaCtx.selectSingleNode("/resp/status/solution");

This throws a "JXPathNotFoundException: No value for xpath". For implementation specific logic, I need to put and if-else block if the expression doesn't return data / doesn't exist.

Any pointer on this will be highly appreciated.

Thanks

2 Answers 2

5

You can prevent the JXPathNotFoundException by setting the context to Lenient:

JXPathContext context = JXPathContext.newContext(myDoc);
context.setLenient(true);

Lenient Mode The context.getValue(xpath) method throws an exception if the supplied xpath does not map to an existing property. This constraint can be relaxed by calling context.setLenient(true). In the lenient mode the method merely returns null if the path maps to nothing.

Sign up to request clarification or add additional context in comments.

1 Comment

The problem with JXPath is that when setLenient is false (default), it raises JXPathNotFoundException when the xPath is invalid OR there's a null in the path. So setting lenient to false exceptions even when the xPath is invalid. The code here oval.sourceforge.net/api/src-html/net/sf/oval/ogn/… sets up a custom JXPath BeanPointerFactory that distinguishes between a null reference and an invalid xPath. This fix should really be rolled into the product itself.
2

Try using JXPathContext.iterate(). It returns an iterator that is empty (hasNext() returns false) when there are no matching nodes. If it has at least one matching node, call next() and return that value. Otherwise return null.

1 Comment

thanks, it's surely a way to address my issue. Wish,they've an evaluate function. Appreciate your help.

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.