Question

@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/>
Was it helpful?

Solution

What @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)

Collection Order

A JAXB implementation will honor the order the items have been added to the List. This matches the behaviour you are seeing.

Getting the Desired Order

  1. You can add the items to the List in the order you want to see them appear in the XML document.
  2. You can have separate properties corresponding to each element and then use propOrder on @XmlType to order the output (see: http://blog.bdoughan.com/2012/02/jaxbs-xmltype-and-proporder.html)
  3. Sort the List property on a JAXB beforeMarshal event.

OTHER TIPS

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);    
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top