background image

The XmlAdapter interface

<< j2s-xmlAdapter-field Example | The XML schema generated >>
<< j2s-xmlAdapter-field Example | The XML schema generated >>
70
U
SING
JAXB
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 j2s-xmlAdapter-field example demonstrates 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". We want these datatypes to be reflected in the XML content that is
read and written. 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>
<xs:element name="entry" minOccurs="0"
maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>