简体   繁体   English

您是否可以使用多组JAXB注释来编组/解组为不同的XML?

[英]Can you have multiple sets of JAXB annotations to marshal/unmarshal to different XML?

We have some entities with JAXB annotations so that we can unmarshal some 'incoming' XML to pojo. 我们有一些带有JAXB批注的实体,因此我们可以将一些“传入” XML编组到pojo。 We now need to marshal the pojos to XML but to a different format than the incoming xml. 现在,我们需要将pojos编组为XML,但格式要不同于传入的xml。 What's the best way of doing this? 最好的方法是什么?

My solution is to use an extra "version" field in the JAXB object to distinguish multiple versions of bindings. 我的解决方案是在JAXB对象中使用一个额外的“版本”字段来区分绑定的多个版本。 Usually, I use enum as its type, ie, enum Version {V1, V2, ...}; 通常,我使用enum作为其类型,即enum版本{V1,V2,...};

So for a specific XML element field, I define the getField() method as 因此,对于特定的XML元素字段,我将getField()方法定义为

@XmlElement
public String getField() {
    if (version == Version.V1) {
        return field;
    } else if (version == Version.V2) {
        return null; // hidden
    }

}

Before marshalling, one just needs to set the version value to the desired enum value, and JAXB will take care of the rest. 在编组之前,只需将版本值设置为所需的枚举值,JAXB将负责其余的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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