A Standalone JAX-B Example
Recall that the B in JAX-B stands for data binding, the associating of a Java data type such as String
to
an XML Schema (or equivalent) type, in this case xsd:string
. There are built-in bindings for the Java
primitive types such as int
and double
together with String
and Calendar
; arrays (including Collections
) of any such
types; and programmer-defined types that reduce, via properties, to any of the preceding. The surprising omission is the
Map
, a collection of key/value pairs, but a Map
is readily handled as two coordinated collections: a collection of
keys and a corresponding collection of values. An example of JAX-B in action may help to drive these points
home.
The Skier
class (see Example 3-4) is annotated with @XmlRootElement
to inform the JAX-B utilities that
a Skier
instance should be
transformed into an XML document that has skier
as its root or document
(that is, outermost) element. In the default Java naming convention, the
root element is the lowercase version of the class name; hence, Skier
becomes skier
. The annotation could be amended:
@XmlRootElement
(
name
=
"NordicSkier"
)
so that the root element has a specified name, in this example NordicSkier
.
Example 3-4. The annotated Skier
POJO class
import
javax.xml.bind.annotation.XmlRootElement
;
import
java.util.Collection
;
@XmlRootElement
public
class
Skier
{
private
Person
person
;
private
String
nationalTeam
;
private
Collection
majorAchievements
;
public
Skier
()
{
}
// required for unmarshaling
Get Java Web Services: Up and Running, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.