How to Implement a Simple Type
Simple types are types that consist only of text, without any elements. Examples for simple types are strings, numbers and dates.
JAXB has the @XmlValue type to implement simple types. To do this, you need to create a Java class to represent the type. Exactly one single property or field of the class must be annotated with the @XmlValue annotation. The property's (or field's) type must always map to a simple type (such as a string or number). The following example implements the class Price as simple type:
@XmlRootElement
public class PriceList {
public List<Price> prices;
}
public class Price {
@XmlValue
public double amount;
public Price(double amount) {
this.amount = amount;
}
public Price() {
}
}
Now the following marshalling code
PriceList priceList = new PriceList();
priceList.prices = Arrays.asList(new Price(99.95), new Price(74.90));
JAXB.marshal(priceList, System.out);
Note that will print this XML document:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<priceList>
<prices>99.95</prices>
<prices>74.9</prices>
</priceList>
Note that there is no <amount> element in the resulting XML, only PriceList's <prices> element.
You can also combine a @XmlValue in a class with an @XmlAttribute. The following example shows you how to use it:
public class Price {
@XmlValue
public double amount;
@XmlAttribute
public String currency;
public Price(double amount, String currency) {
this.amount = amount;
this.currency = currency;
}
public Price() {
}
}
Then the following code
PriceList priceList = new PriceList();
priceList.prices = Arrays.asList(new Price(99.95, "US Dollar"), new Price(74.90, "Euro"));
JAXB.marshal(priceList, System.out);
will print this XML document:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<priceList>
<prices currency="US Dollar">99.95</prices>
<prices currency="Euro">74.9</prices>
</priceList>
Not every @XmlValue property needs to be backed by an actual field, of course. You can also use it to construct a simple typed value from several other values:
public class Price {
private double amount;
private String currency;
public Price(double amount, String currency) {
this.amount = amount;
this.currency = currency;
}
public Price() {
}
@XmlValue
public String getValue() {
return amount + " " + currency;
}
public void setValue(String v) { // bad code, no error handling!
amount = Double.parseDouble(v.replaceFirst("\\s.*$", ""));
currency = v.replaceFirst("^.*\\s", "");
}
}
When using the same content tree as in the previous example, the resulting XML will be:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<priceList>
<prices>99.95 US Dollar</prices>
<prices>74.9 Euro</prices>
</priceList>

