简体   繁体   中英

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. We now need to marshal the pojos to XML but to a different format than the incoming 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. Usually, I use enum as its type, ie, enum Version {V1, V2, ...};

So for a specific XML element field, I define the getField() method as

@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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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