@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/>
答案 0 :(得分:4)
@XmlElements
是什么 @XmlElements
对应于XML Schema中的choice
结构。属性对应于多个元素(请参阅:http://blog.bdoughan.com/2010/10/jaxb-and-xsd-choice-xmlelements.html)
JAXB实现将遵守项目已添加到List
的顺序。这符合您所看到的行为。
List
。propOrder
上的@XmlType
来排序输出(请参阅:http://blog.bdoughan.com/2012/02/jaxbs-xmltype-and-proporder.html)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);
}