prev table of contents next

6.2.7.4 Mapping a Class to Simple Content or Simple Type: XmlValue

Usually a Java class results in a complex type, with one element or attribute for each field. Now consider this simple Java class with a single instance variable:

public class Price {
    private BigDecimal amount;
    public Price(){}
    @XmlElement
    public BigDecimal getAmount(){
	return amount;
    }
    public void setAmount( BigDecimal value ){
	this.amount = value;
    }
}
If this type is used for some field, the result will be according to this XML Schema type definition:
<xs:complexType name="price">
  <xs:sequence>
    <xs:element name="amount" type="xs:decimal" minOccurs="0"/>
  </xs:sequence>
</xs:complexType>
The marshalled XML data is unnecessarily complicated due to an addtional element layer, e.g.:
<price>
  <amount>123.45</amount>
</price>
What is required here is a way of telling JAXB to map class Price to a simple schema type. This is done by annotating the single field amount with XmlValue instead of XmlElement:
public class Price {
    // ...
    @XmlValue
    public BigDecimal getAmount(){
	return amount;
    }
    // ...
}
This is now equivalent to this simple type definition:
<xs:simpleType name="price">
  <xs:restriction base="xs:decimal"/>
</xs:simpleType>
The XML data is pleasantly reduced to:
<price>123.45</price>
Notice that fields of type Price could now be mapped to an XML attribute, too.


prev table of contents next