Reputation: 315
I am having trouble figuring out how to create a POJO model for simplexml.
Say I have an xml that I want to extract data from that looks like this:
<root>
<station>
<station>
<abbr>Abbr1</abbr>
</station>
</station>
<station>
<station>
<abbr>Abbr2</abbr>
</station>
</station>
<station>
<station>
<abbr>Abbr3</abbr>
</station>
</station>
</root>
So basically I figured I have an array inside of an Array, So I coded my java model like this:
@org.simpleframework.xml.Root(name="root")
public class Root {
@Element(name="stations")
public Stations stations;
@Element(name="station")
public Station[] station;
@Element(name="abbr")
public String abbr;
public class Stations{
public Station[] station;
}
public class Station{
public String abbr;
}
}
I tried tweaking the annotations around, but I can't get this to work. I would really appreciate help on this, thank you.
Upvotes: 1
Views: 2057
Reputation: 2527
I find the XML structure a bit odd as the child-station tags seem redundant. Nevertheless, if this is what you're going for then these are the annotated POJO's that could work for you (I replaced your 'Root' class with 'MyResponse'):
@Root
public class Station {
@Path("station")
@Element(name = "abbr") String abbr;
}
@Root
public class MyResponse {
@ElementList(entry = "station", inline = true)
ArrayList<Station> stationsList;
}
Namely, I've used @ElementList
to annotate the list of parent 'station' tags instead of plain @Element
annotations: The simple xml frameworks has both @ElementList
and @ElementArray
for those cases, and I prefer the former.
In addition, since it seems the child 'station' tags have no actual usage I've "skipped" over them by using the @Path
annotation.
If you wish to read more about these techniques, try looking into the Simple XML documentation on lists.
Upvotes: 2