@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 的父类(super class)
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
的顺序。这与您看到的行为相符。
获得想要的订单
- 您可以按照希望在 XML 文档中显示的顺序将项目添加到
List
。 - 您可以拥有与每个元素相对应的单独属性,然后使用
@XmlType
上的propOrder
对输出进行排序(参见:http://blog.bdoughan.com/2012/02/jaxbs-xmltype-and-proporder.html) - 对 JAXB
beforeMarshal
事件的List
属性进行排序。
关于java - JAXB @XmlElements 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20782283/