The Java EE 5 Tutorial

XmlAttribute Field Example

The XmlAttribute Field example shows how to use the @XmlAttribute annotation to define a property or field to be treated as an XML attribute.

The @XmlAttribute annotation maps a field or JavaBean property to an XML attribute. The following rules are imposed:

When following the JavaBean programming paradigm, a property is defined by a get and set prefix on a field name.

int zip;
public int getZip(){return zip;}
public void setZip(int z){zip=z;}

Within a bean class, you have the choice of setting the @XmlAttribute annotation on one of three components: the field, the setter method, or the getter method. If you set the @XmlAttribute annotation on the field, the setter method will need to be renamed or there will be a naming conflict at compile time. If you set the @XmlAttribute annotation on one of the methods, it must be set on either the setter or getter method, but not on both.

The XmlAttribute Field example shows how to use the @XmlAttribute annotation on a static final field, on a field rather than on one of the corresponding bean methods, on a bean property (method), and on a field that is other than a collection type. In class USAddress, fields, country, and zip are tagged as attributes. The setZip method was disabled to avoid the compile error. Property state was tagged as an attribute on the setter method. You could have used the getter method instead. In class PurchaseOrderType, field cCardVendor is a non-collection type. It meets the requirement of being a simple type; it is an enum type.

Building and Running the XmlAttribute Field Example Using NetBeans IDE

Follow these instructions to build and run the XmlAttribute Field example on your Application Server instance using the NetBeans IDE.

  1. In NetBeans IDE, select File->Open Project.

  2. In the Open Project dialog, navigate to tut-install/javaeetutorial5/examples/jaxb/.

  3. Select the j2s-xmlAttribute-field folder.

  4. Select the Open as Main Project check box.

  5. Click Open Project.

  6. Right-click the j2s-xmlAttribute-field project and select Run.

Building and Running the XmlAttribute Field Example Using Ant

To compile and run the XmlAttribute Field example using Ant, in a terminal window, go to the tut-install/javaeetutorial5/examples/jaxb/j2s-xmlAttribute-field/ directory and type the following:


ant runapp