I have an XML structure that I want to unmarshal using JaxB, while maintaining the order:
<body>
<apple>
<!-- ... -->
</apple>
<banana>
<!-- ... -->
</banana>
<apple>
<!-- ... -->
</apple>
</body>
With this snippet I get the desired output
@XmlElement(name = "apple")
List<Apple> apples;
@XmlElement(name = "banana")
List<Banana> bananas;
// getters & setter
I get the desired output, but in the "wrong" order. So if I iterate the lists, I would get
1. Apple
2. Apple
3. Banana
In the XML above, the order was:
1. Apple
2. Banana
3. Apple
My idea was to make an abstract class (or interface) Fruit, so that Apple and Banana can extend from it:
abstract class Fruit{}
class Apple extends Fruit{
//...
}
class Banana extends Fruit{
//...
}
Then unmarshal the elements Apple and Banana into a (Linked-)List of Fruit
s, as shown here:
List<Fruit> fruits;
@XmlElements({
@XmlElement(name = "apple", type = Apple.class),
@XmlElement(name = "banana", type = Banana.class)
})
@XmlElementWrapper
public List<Fruit> getFruits() {
return fruits;
}
Unfortunately, fruits
stays null
.