String javax.xml.xpath.XPathExpression.evaluate(Object item) guarantees it never returns null in all implementations?

StackOverflow https://stackoverflow.com/questions/1985234

  •  22-09-2019
  •  | 
  •  

Question

From the JavaDoc: returns: The String that is the result of evaluating the expression and converting the result to a String.

/**
 * ...
 * ...
 * @return The <code>String</code> that is the result of evaluating the expression and converting the result to a 
 *   <code>String</code>.
 * ...
 * ...
 */
String javax.xml.xpath.XPathExpression.evaluate(Object item)

The question is, it is a bit vauge what is the contract here in case the expression finds nothing. Is null an valid / invalid return in all implementations? where is the return API defined? in the JSR?

Was it helpful?

Solution

If I remember correctly, there is no such thing as null in XPath. My guess would be it returns the empty string.

Update: a quick look at XPath 2.0 and XPath 2.0 Functions specs confirms this feeling.

OTHER TIPS

This could be not an expected answer.

<types>
    <type id="1">
        <href>aaa</href>
    </type>
</types>

Lets say you wrote a method finds @id by href.

Double findIdByHref(final String href) {
    evaluate("/:types/:type[:href='bbb']/@id", NUMBER);
}

This method returns 0 not null for bbb as href

final Double id = findByHref("bbb"); // not null

I had to modify like this

Double findIdByHref(final String href) {
    final Node node = evaluate("/:types/:type[:href='bbb']", NODE);
    if (node == null) {
        return null;
    }
    return evaluate("@id", node);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top