Jump to: navigation, search


< EclipseLink‎ | Examples‎ | MOXy‎ | GettingStarted
Revision as of 15:27, 8 January 2010 by Blaise.doughan.oracle.com (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)


This example will build upon the lessons learned in the previous example (The Basics), and demonstrate how JAXB annotations can be used to customize the XML output.

Customizing a Type

In the previous example (The Basics) we required a supplementary object to serve as the root of our model. When can use JAXB annotations to specify which classes in our domain model can serve as roots, this is done using the @XmlRootElement annotation. Now that this annotation has been added we no longer require the use of the JAXBElement class.

By default the order in which the XML elements are marshalled out is dependent on the implementation. We can control the order using the propOrder property on the JAXB annotation @XmlType.

package example.gettingstarted;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlType(propOrder={"name", "address", "phoneNumbers"})
public class Customer {
    private String name;
    private Address address;
    private List<PhoneNumber> phoneNumbers;
    public Customer() {
        phoneNumbers = new ArrayList<PhoneNumber>();
    public String getName() {
        return name;
    public void setName(String name) {
        this.name = name;
    public Address getAddress() {
        return address;
    public void setAddress(Address address) {
        this.address = address;
    public List<PhoneNumber> getPhoneNumbers() {
        return phoneNumbers;
    public void setPhoneNumbers(List<PhoneNumber> phoneNumbers) {
        this.phoneNumbers = phoneNumbers;

Customizing a Property

By default Java properties are mapped to XML elements. In order to map a property to an XML attribute the JAXB annotation @XmlAttribute is used. If you want to map a property directly to a text field without an element wrapper simply use the JAXB annotation @XmlValue.

package example.gettingstarted;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlValue;
public class PhoneNumber {
    private String type;
    private String number;
    public String getType() {
        return type;
    public void setType(String type) {
        this.type = type;
    public String getValue() {
        return number;
    public void setValue(String value) {
        this.number = value;