使用jxpath通过特定属性在数组中查找元素

时间:2019-06-30 09:20:42

标签: java xpath jxpath

下面的代码中的JXpath表达式有什么问题?以下代码始终会引发此异常:

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

但是我希望德国回归。怎么了?

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;
    }
}

2 个答案:

答案 0 :(得分:1)

我对所使用的jxpath库了解不多。但是xpath表达式应该像这样:

/countries/country[gdp=4]

答案 1 :(得分:1)

更换后,它开始工作:

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

通过:

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