background image

Interface XmlAdapter

<< Schema Content Ordering in the Example | HashMap Schema >>
<< Schema Content Ordering in the Example | HashMap Schema >>

Interface XmlAdapter

Interface XmlAdapter and annotation @XmlJavaTypeAdapter are used for special processing of
data types during unmarshalling/marshalling. There are a variety of XML data types for which
the representation does not map easily into Java (for example, xs:DateTime and xs:Duration),
and Java types which do not map conveniently into XML representations, for example
implementations of java.util.Collection (such as List) and java.util.Map (such as
HashMap
) or for non-JavaBean classes.
The XmlAdapter interface and the @XmlJavaTypeAdapter annotation are provided for cases
such as these. This combination provides a portable mechanism for reading/writing XML
content into and out of Java applications.
The XmlAdapter interface defines the methods for data reading/writing.
/*
*
ValueType - Java class that provides an XML representation
*
of the data. It is the object that is used for
*
marshalling and unmarshalling.
*
*
BoundType - Java class that is used to process XML content.
*/
public abstract class XmlAdapter<ValueType,BoundType> {
// Do-nothing constructor for the derived classes.
protected XmlAdapter() {}
// Convert a value type to a bound type.
public abstract BoundType unmarshal(ValueType v);
// Convert a bound type to a value type.
public abstract ValueType marshal(BoundType v);
}
You can use the @XmlJavaTypeAdapter annotation to associate a particular XmlAdapter
implementation with a Target type, PACKAGE, FIELD, METHOD, TYPE, or PARAMETER.
The XmlAdapter Field example shows how to use an XmlAdapter for mapping XML content
into and out of a (custom) HashMap. The HashMap object, basket, in class KitchenWorldBasket,
uses a key of type int and a value of type String. These data types should be reflected in the
XML content that is read and written, so the XML content should look like this.
<basket>
<entry key=
"9027">glasstop stove in black</entry>
<entry key=
"288">wooden spoon</entry>
</basket>
The default schema generated for Java type HashMap does not reflect the desired format.
<xs:element name=
"basket">
<xs:complexType>
<xs:sequence>
Java-to-Schema Examples
Chapter 17 · Binding between XML Schema and Java Classes
541