@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 回答
@XmlElements是为了什么
@XmlElements
对应于XML Schema中的choice
结构 . 属性对应多个元素(参见:http://blog.bdoughan.com/2010/10/jaxb-and-xsd-choice-xmlelements.html)收集订单
JAXB实现将遵守项目已添加到
List
的顺序 . 这符合您所看到的行为 .获得所需订单
您可以按照希望在XML文档中显示的顺序将项目添加到
List
.您可以拥有与每个元素对应的单独属性,然后在
@XmlType
上使用propOrder
来对输出进行排序(请参阅:http://blog.bdoughan.com/2012/02/jaxbs-xmltype-and-proporder.html)在JAXB
beforeMarshal
事件上对List
属性进行排序 .使用比较器解决: