I have an object that I get back from a REST API in XML format. I can create and update this object type. In my Rest client, I want to supply an attribute with some of my elements. Let's say I can specify an attribute like access="LOCKED" to make that field read-only in the user interface.
Example: User Object
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "User")
public class User {
private String userName;
private String userId;
private String firstName;
private String lastName;
private String email;
@XmlAttribute(name="username")
public void setUserName(String userName) {
this.userName = userName;
}
@XmlAttribute(name = "userId", namespace = "some namespace")
public void setUserId(String userId) {
this.userId = userId;
}
@XmlElement(name = "FirstName")
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@XmlElement(name = "LastName")
public void setLastName(String lastName) {
this.lastName = lastName;
}
@XmlElement(name = "Email")
public void setEmail(String email) {
this.email = email;
}
}
Marshaling with JAXB:
User user = User.builder().email("e@mail.com").userName("jd")
.userId("123").firstName("Jane").lastName("Doe").build();
JAXBContext jaxbContext = JAXBContext.newInstance(Iser.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(user, System.out);
Assuming that I want to set the access for Email and LastName, How would you annotate this "access" attribute to put it on each of these Elements?
Expected output with the access attribute:
<User username="jd" ns:userId="123">
<FisrtName>Jane</FirstName>
<LastName access="LOCKED">Doe</LastName>
<Email access="LOCKED">e@mail.com</Email>
</User>