Reputation: 691
I got following XML with element name being present with their package name. How can I marshal/unmarshal the given XML using JaxB?
<com.jaraws.api.Vehicle>
<number>KT12356</number>
<engine>DIESEL<engine>
</com.jaraws.api.Vehicle>
With Java class being written as:
package com.jaraws.api;
@XmlRootElement
public class Vehicle{
private String number;
private String engine;
// Getters Setter for number and engine attributes
@XmlElement
public String getNumber(){
return number;
}
public void setNumber(){
this.number=number;
}
@XmlElement
public String getEngine(){
return engine;
}
public void setEngine(){
this.engine=engine;
}
}
Is it achievable or I am not doing something in a right matter. I want to marshal / unmarshal the xml in given format only.
Upvotes: 0
Views: 57
Reputation: 2848
As suggested by Thomas in the comments, just add the name
attribute to the @XmlRootElement
annotation to the name you expect :
@XmlRootElement(name = "com.jaraws.api.Vehicle")
public class Vehicle {
// class definition ...
}
You can't do something like the following :
@XmlRootElement(name = Vehicle.class.getName())
If you try to, you'll get the following error : The value for annotation attribute XmlRootElement.name must be a constant expression
By default, according to javadoc, if name is not set, it's derived from the class name :
public @interface XmlRootElement {
// some stuff
/**
* local name of the XML element.
* <p>
* If the value is "##default", then the name is derived from the
* class name.
*
*/
String name() default "##default";
}
Not specifying the name element will then lead to the following name vehicle
(see org.glassfish.jaxb.runtime.v2.model.impl.TypeInfoImpl#parseElementName
method for more info)
Upvotes: 0