Annotations [@XmlElement](<https://docs.oracle.com/javase/8/docs/api/javax/xml/bind/annotation/XmlElement.html>)
, [@XmlAttribute](<https://docs.oracle.com/javase/8/docs/api/javax/xml/bind/annotation/XmlAttribute.html>)
or [@XmlTransient](<https://docs.oracle.com/javase/8/docs/api/javax/xml/bind/annotation/XmlTransient.html>)
and other in package [javax.xml.bind.annotation](<https://docs.oracle.com/javase/8/docs/api/javax/xml/bind/annotation/package-summary.html>)
allow the programmer to specify which and how marked fields or properties should be serialized.
@XmlAccessorType(XmlAccessType.NONE) // we want no automatic field/property marshalling
public class ManualXmlElementsExample {
@XmlElement
private String field="field value";
@XmlAttribute
private String attribute="attr value";
@XmlAttribute(name="differentAttribute")
private String oneAttribute="other attr value";
@XmlElement(name="different name")
private String oneName="different name value";
@XmlTransient
private String transientField = "will not get serialized ever";
@XmlElement
public String getModifiedTransientValue() {
return transientField.replace(" ever", ", unless in a getter");
}
public void setModifiedTransientValue(String val) {} // empty on purpose
public static void main(String[] args) {
try {
JAXB.marshal(new ManualXmlElementsExample(), System.out);
} catch (Exception e) {
System.err.println("Exception occurred while writing in XML!");
}
}
}