开发者

How to evaulate xpath expression using JXpath library

开发者 https://www.devze.com 2023-04-12 03:45 出处:网络
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 lin

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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消