JAXB @XmlElements订单

hid*_*ser 6 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;
Run Code Online (Sandbox Code Playgroud)

其中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/>
Run Code Online (Sandbox Code Playgroud)

但需要按照内部声明的顺序 @XmlElements({})

<house/>
<message/>
<animal/>
<animal/>
Run Code Online (Sandbox Code Playgroud)

bdo*_*han 4

@XmlElements用途是什么

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

托收订单

JAXB 实现将遵循项目添加到List. 这与您所看到的行为相符。

获得所需的订单

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