首页 文章

JAXB @XmlElements订单

提问于
浏览
5
@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 回答

  • 1

    @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 属性进行排序 .

  • 4

    使用比较器解决:

    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);    
    }
    

相关问题