1

What is wrong with the JXpath expression in the code below? The following code always throws this exception:

org.apache.commons.jxpath.JXPathNotFoundException: No value for xpath: countries[gdp=4]

However I expected the country Germany to be returned. Whats wrong here?

import org.apache.commons.jxpath.JXPathContext;

public class Test {

    private final Country[] countries = {
        new Country("US", 20),
        new Country("China", 13),
        new Country("Japan", 5),
        new Country("Germany", 4),
        new Country("UK", 3)};

    public static void main(String[] args) {
        Object result = JXPathContext.newContext(new Test()).getValue("countries[gdp=4]");
        System.out.println(result);
    }

    public Country[] getCountries() {
        return countries;
    }   
}

-

class Country{

    private String name;
    private int gdp;

    public Country(String name, Integer gdp){
        this.name=name;
        this.gdp=gdp;
    }

    @Override
    public String toString() {
        return name;
    }

    public String getName() {
        return name;
    }

    public int getGdp() {
        return gdp;
    }
}
eztam
  • 3,443
  • 7
  • 36
  • 54

2 Answers2

1

I don't know enough about the jxpath lib you are using. But the xpath expression should be like this:

/countries/country[gdp=4]
Thilo Schwarz
  • 640
  • 5
  • 24
  • I've verified the xpath expression with an online xpath tester like [Xpath-Tester](https://codebeautify.org/Xpath-Tester) and it's valid. But I don't now, how to implement this with jxpath, sorry. – Thilo Schwarz Jul 01 '19 at 08:00
1

It started to work after I replaced:

Object result = JXPathContext.newContext(new Test()).getValue("countries[gdp=4]");

By:

Iterator result = JXPathContext.newContext(new Test()).iterate("countries[gdp=4]");
eztam
  • 3,443
  • 7
  • 36
  • 54