2016-11-13 39 views
0

我正在解组从世界银行网络服务获取的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

相关问题