You are viewing a plain text version of this content. The canonical link for it is here.
Posted to user@commons.apache.org by Shamik Bandopadhyay <sh...@gmail.com> on 2011/10/12 01:12:32 UTC

[jxpath] How to evaulate xpath expression using JXpath library

Hi,
     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" is solution is
not presenet. 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