java - JAXB ClassCastException due to root element having the same tag as its child element -
i unmarshalling xml file taken world bank web service. root element , children elements have same tag, shown below. getting classcastexception when unmarshalling. error goes away when change root element tag not same children.
is jaxb unable handle scenario or not using jaxb properly?
<data> <data> </data> ...... <data> </data> </data>
here java code reference:
xml tag issue: http://api.worldbank.org/countries/all/indicators/sp.pop.totl?format=xml
main 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()); } }
root element 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; } }
child element class
@xmlaccessortype(xmlaccesstype.field) @xmlrootelement(name = "data") public class countrypop { @xmlelement(name="date") private int date; public int getdate() { return date; } }
just remove @xmlrootelement(name = "data")
countrypop
class following:
@xmlaccessortype(xmlaccesstype.field) public class countrypop { @xmlelement(name="date") private int date; public int getdate() { return date; } }
and if handling namespace wb should work fine.
Comments
Post a Comment