[英]JAXB @XmlElements Order
@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/>
@XmlElements
是做什么用的 @XmlElements
对应于XML Schema中的choice
结构。 一个属性对应于多个元素(请参阅: http : //blog.bdoughan.com/2010/10/jaxb-and-xsd-choice-xmlelements.html )
JAXB实现将接受将项目添加到List
的顺序。 这与您看到的行为相匹配。
List
中。 @XmlType
上使用propOrder
对@XmlType
进行排序(请参阅: http : @XmlType
) beforeMarshal
事件的List
属性进行排序。 使用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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.