Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAXB: Change name of XML Element from Java code?

Tags:

java

xml

jaxb

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?

like image 998
punkyduck Avatar asked Nov 05 '11 16:11

punkyduck


1 Answers

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.

  • http://blog.bdoughan.com/2010/12/extending-jaxb-representing-annotations.html

For a Detailed Example

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

  • http://blog.bdoughan.com/2011/09/mapping-objects-to-multiple-xml-schemas.html
like image 119
bdoughan Avatar answered Oct 23 '22 05:10

bdoughan