【发布时间】:2016-11-13 00:51:48
【问题描述】:
我正在解组从世界银行网络服务获取的 XML 文件。根元素和子元素具有相同的标签,如下所示。解组时出现 ClassCastException。当我更改根元素标记使其与其子元素不同时,此错误消失。
是 JAXB 无法处理这种情况还是我没有正确使用 JAXB?
<data>
<data>
</data>
......
<data>
</data>
</data>
这是我的 Java 代码供参考:
带有标签问题的 XML:http://api.worldbank.org/countries/all/indicators/SP.POP.TOTL?format=xml
主类
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());
}
}
根元素类
@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;
}
}
子元素类
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "data")
public class CountryPop {
@XmlElement(name="date")
private int date;
public int getDate() {
return date;
}
}
【问题讨论】:
标签: java xml jaxb classcastexception