JAXB @XmlElements Order
Asked Answered
A

2

6
@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/>
Apartheid answered 26/12, 2013 at 9:24 Comment(1)
@XmlElements is just acts as a container to have multiple @XmlElement. Can you elaborately mention your actual need and with Code?Matriculate
A
4

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.
Ainslee answered 26/12, 2013 at 10:34 Comment(4)
So is there a way to achieve the order in Collection ?Apartheid
@userG - I have updated my answer with a couple ways to get the desired ordering.Ainslee
Is there any other way using Collection Tree to sort object on void beforeMarshal(Marshaller marshaller) listener ?Apartheid
@userG - Yes you could do that. I have updated my answer to include that approach.Ainslee
A
1

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);    
}
Apartheid answered 26/12, 2013 at 12:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.