JAXB ClassCastException 由于根元素具有与其子元素相同的标签

JAXB ClassCastException due to root element having the same tag as its child element

我正在解组来自世界银行网络服务的 XML 文件。根元素和子元素具有相同的标记,如下所示。解组时出现 ClassCastException。当我更改根元素标签以使其与其子元素标签不同时,此错误消失。

是 JAXB 无法处理这种情况还是我没有正确使用 JAXB?

<data>
    <data>
    </data>
    ......
    <data>
    </data>
</data>

这是我的Java代码供参考:

XML 标签问题:http://api.worldbank.org/countries/all/indicators/SP.POP.TOTL?format=xml

主要class

public class CountryPopParse {
    public List<CountryPop> parse() throws JAXBException, MalformedURLException, IOException{
        JAXBContext jc = JAXBContext.newInstance(CountryPops.class);
        Unmarshaller u = jc.createUnmarshaller();
        URL url = new URL("http://api.worldbank.org/countries/all/indicators/SP.POP.TOTL?format=xml");
        CountryPops countryPops = (CountryPops) u.unmarshal(url);
        return countryPops.getCountryPop();
    }  

    public static void main(String[] args) throws JAXBException, IOException, SQLException{
        CountryPopParse p = new CountryPopParse();
        List<CountryPop> popList= p.parse();
        System.out.println(popList.get(0).getDate());
    } 
}

根元素class

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "data")
public class CountryPops {

    @XmlElement(name = "data", type = CountryPop.class)
    private List<CountryPop> countryPops = new ArrayList<>();

    public CountryPops(){        
    }

    public CountryPops(List<CountryPop> countryPops) {
        this.countryPops = countryPops;
    }

    public List<CountryPop> getCountryPop() {
        return countryPops;
    }
}

子元素class

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "data")
public class CountryPop {

    @XmlElement(name="date")
    private int date;

    public int getDate() {
        return date;
    }    
}

只需从 CountryPop class 中删除 @XmlRootElement(name = "data"),如下所示:

@XmlAccessorType(XmlAccessType.FIELD)
public class CountryPop {
    @XmlElement(name="date")
    private int date;

    public int getDate() {
        return date;
    }    
}

如果您正在处理命名空间 wb 应该可以正常工作。