I'm learning how to use java XPath API and I got a question about behavior of evaluate() method of XPathExpression class.
I have XML file that contains data about employees.
I want to find highest payed employee in form of String, so I write this code:
FileInputStream file = new FileInputStream(new File
("D:\\workspace\\NetCrackerTasks\\src\\ru\\ncedu\\java\\tasks\\emp.xml"));
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document src = builder.parse(file);
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "/content/emp/employee[not(../employee/sal > xs:decimal(sal))]";
String result = null;
XPathExpression expr = null;
try {
expr = xPath.compile(expression);
result = expr.evaluate(src); //This throws NullPointerException
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return result;
When I run this code in Eclipse, expr.evaluate(src)
throws NullPointerException.
In documentation on docs.oracle.com(link) it says that
If source is null, then a NullPointerException is thrown.
I checked my src
object and it is not null, and path to xml document is right.
So my question is: why do I get NullPointerException?
And isn't there more proper way to get elements of XML document in form of a String that match XPath expression?
My XML file looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<content
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="ns:emp"
xsi:schemaLocation="ns:emp emp.xsd">
<emp>
<employee deptno="10" empno="7369" mgr="7902">
<ename>SMITH</ename>
<job>CLERK</job>
<hiredate>1980-12-17</hiredate>
<sal>800.00</sal>
<comm>0.0</comm>
</employee>
<employee deptno="30" empno="7521" mgr="7698">
<ename>WARD</ename>
<job>SALESMAN</job>
<hiredate>1981-02-22</hiredate>
<sal>1250.00</sal>
<comm>500.00</comm>
</employee>
<employee deptno="20" empno="7566" mgr="7839">
<ename>JONES</ename>
<job>MANAGER</job>
<hiredate>1981-04-02</hiredate>
<sal>2975.00</sal>
<comm>0.0</comm>
</emp>
</content>
EDIT: xPath.compile(expression);
does not return null and expr
is not null when expr.evaluate(src)
runs. So NullPointerException is thrown not becuase calling a method on a null object, because object is not null.