@XmlElements({
@XmlElement(name = "house", type = House.class),
@XmlElement(name = "error", type = Error.class),
@XmlElement(name = "message", type = Message.class),
@XmlElement(name = "animal", type = Animal.class)
})
protected List<RootObject> root;
where RootObject is super class of House,Error,Message,Animal
root.add(new Animal());
root.add(new Message());
root.add(new Animal());
root.add(new House());
//Prints to xml
<animal/>
<message/>
<animal/>
<house/>
but needs in order as declared inside @XmlElements({})
<house/>
<message/>
<animal/>
<animal/>
@XmlElements
is For @XmlElements
corresponds to the choice
structure in XML Schema. A property corresponds to more than one element (see: http://blog.bdoughan.com/2010/10/jaxb-and-xsd-choice-xmlelements.html )
A JAXB implementation will honor the order the items have been added to the List
. This matches the behaviour you are seeing.
List
in the order you want to see them appear in the XML document. propOrder
on @XmlType
to order the output (see: http://blog.bdoughan.com/2012/02/jaxbs-xmltype-and-proporder.html ) List
property on a JAXB beforeMarshal
event. Resolved using Comparator :
static final Comparator<RootObject> ROOTELEMENT_ORDER =
new Comparator<RootObject>() {
final List<Class<? extends RootObject>> classList = Arrays.asList(
House.class,Error.class, Message.class, Animal.class );
public int compare(RootObject r1, RootObject r2) {
int i1 = classList.indexOf(r1.getClass());
int i2 = classList.indexOf(r2.getClass());
return i1-i2 ;
}
};
void beforeMarshal(Marshaller marshaller ) {
Collections.sort(root, ROOTELEMENT_ORDER);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.