Not sure if the title makes any sense. I have an object that I want to marshal using JAXB that looks like this:
@XmlRootElement(name = "subscriptionRequest")
public class RegistrationRequest {
private Long id;
private RegistrationSource registrationSource;
}
The RegistrationSource object:
public class RegistrationSource {
private Integer id;
private String code;
}
I want to create an xml that has the following layout:
<subscriptionRequest registrationSource="0002">
...
</subscriptionRequest>
where the registrationSource attribute value is the code field value from the RegistrationSource object.
What xml annotations do I need to use?
@XmlAttribute on registrationSource, @XmlValue on code. Note that in this case you also should have @XmlTransient on other fields of RegistrationSource, such as id
EDIT: This works:
@XmlRootElement(name = "subscriptionRequest")
public class RegistrationRequest {
private Long id;
private RegistrationSource registrationSource;
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
@XmlAttribute
public RegistrationSource getRegistrationSource() { return registrationSource; }
public void setRegistrationSource(RegistrationSource registrationSource)
{
this.registrationSource = registrationSource;
}
}
-
public class RegistrationSource {
private Integer id;
private String code;
@XmlTransient
public Integer getId() { return id; }
public void setId(Integer id) { this.id = id; }
@XmlValue
public String getCode() { return code; }
public void setCode(String code) { this.code = code; }
}
If you want to generate this class automatically using some tools , then try this - Generate xsd from your xml using tools like Trang, and then generate java file from xsd using jaxb. Life would be much simpler :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With