繁体   English   中英

JAXB @XmlElements顺序

[英]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的顺序。 这与您看到的行为相匹配。

获取所需的订单

  1. 您可以按照希望它们在XML文档中出现的顺序将它们添加到List中。
  2. 您可以具有与每个元素对应的单独属性,然后在@XmlType上使用propOrder@XmlType进行排序(请参阅: http : @XmlType
  3. 对JAXB 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM