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
importjavax.xml.bind.annotation.XmlRootElement;importjava.util.Collection;@XmlRootElementpublicclassSkier{privatePersonperson;privateStringnationalTeam;privateCollectionmajorAchievements;publicSkier(){}// required for unmarshaling
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access