JAXB: Change name of XML Element from Java code?

16,107

Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB 2 (JSR-222) expert group.

You can use the external mapping document extension in MOXy JAXB to apply a second mapping to your object model. This mapping document can be be used to modify metadata provided via annotations, or completely replace it.

For a Detailed Example

In the example below a single object model is mapped to the results of the Google and Yahoo weather APIs:

Share:
16,107
punkyduck
Author by

punkyduck

Updated on June 28, 2022

Comments

  • punkyduck
    punkyduck almost 2 years

    To set the name of an XML element I use annotations like this:

    @XmlElement(name = "customer_id")
    public String getId(){}
    

    I have to communicate with two different webservices. One expacts an id element named customer_id but the other expacts the id element to be named id. I solved the problem by creating a second Customer class with the same attributes. The only different is that it uses the following annotation

    @XmlElement(name = "id")
    public String getId(){}
    

    and it has a copy constructor which copies all attributes from Customer1 to Customer2. When I am communicating with the first webservice I send a Customer1 object and the other webservice gets a Customer2 object.

    Is there any possibility to use only one Customer object, but rename the id attribute to whatever the webservice expects?