2016-11-13 7 views
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; 
    }  
} 

答えて

0

ただ、次のようなCountryPopクラスから@XmlRootElement(name = "data")を削除:

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

    public int getDate() { 
     return date; 
    }  
} 

そして、あなたは WB名前空間を処理している場合は正常に動作する必要があります。

+0

ありがとうございます! – daintym0sh

関連する問題