0
World Bank Webサービスから取得したXMLファイルのアンマーシャリングを行っています。以下に示すように、ルート要素と子要素には同じタグがあります。アンマーシャリング時にClassCastExceptionが発生します。このエラーは、子エレメントと同じでないようにルートエレメントタグを変更すると消えてしまいます。子要素と同じタグを持つルート要素によるJAXB 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;
}
}
ありがとうございます! – daintym0sh