JXPath getValue results include results from previous searches as well

157 views Asked by At

I am using JXPathContext to search through the Java Object using XPath. I have the following code. The class department has an employees collection.

public List<Employee> getEmployeesByDepartment(String departmentName, Company company){
    JXPathContext context = JXPathContext.newContext(company);
    context.setLenient(true);

    @SuppressWarnings("unchecked")
    List<Employee> employees = (List<Employee>) context
            .getValue("/company[department/name ='"+departmentName+"']/department/employee");

    return employees;
}

For example, I make the first call for department HR and then the second call for Accounts. The list returned after the second call will contain employees from Accounts as well as the HR department.

1

There are 1 answers

0
Will Goring On

Your XPath is selecting all employees in all departments in all companies that have a department with the specified name. It'll be doing this on all searches, not only later ones. To only select employees within the named department:

"/company/department[name ='" + departmentName + "']/employee"

You probably also want a predicate on the company name, but I don't know what your xml looks like, so I can't advise you on that.