Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAXB @XmlElements Order

Tags:

java

xml

jaxb

jaxb2

@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/>
like image 398
hiddenuser Avatar asked Dec 26 '13 09:12

hiddenuser


2 Answers

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.
like image 184
bdoughan Avatar answered Oct 05 '22 00:10

bdoughan


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);    
}
like image 34
hiddenuser Avatar answered Oct 04 '22 22:10

hiddenuser