JAXB @XmlElements订单

时间:2013-12-26 09:24:22

标签: 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;

其中RootObject是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/>

但需要在@XmlElements({})

中声明的顺序
<house/>
<message/>
<animal/>
<animal/>

2 个答案:

答案 0 :(得分:4)

@XmlElements是什么

@XmlElements对应于XML Schema中的choice结构。属性对应于多个元素(请参阅:http://blog.bdoughan.com/2010/10/jaxb-and-xsd-choice-xmlelements.html

收集订单

JAXB实现将遵守项目已添加到List的顺序。这符合您所看到的行为。

获得所需订单

  1. 您可以按照希望在XML文档中显示的顺序将项目添加到List
  2. 您可以拥有与每个元素相对应的单独属性,然后使用propOrder上的@XmlType来排序输出(请参阅:http://blog.bdoughan.com/2012/02/jaxbs-xmltype-and-proporder.html
  3. 对JAXB List事件中的beforeMarshal属性进行排序。

答案 1 :(得分:1)

使用比较器解决:

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);    
}