Reputation: 206
I create XML with JAXB, and I want to put double inside tags:
@XmlElement(name = "TaxFree")
private double taxFreeValue;
When I set value with setTaxFreeValue(4.5);
in tags shows <TaxFree>4.5<TaxFree>
Is it possible in JAXB to get this <TaxFree>4.500<TaxFree>
without transfer double to string?
Upvotes: 8
Views: 7683
Reputation: 11
The cleanest way I've found is to use XMLAdapter
. Create a DoubleAdapter
class with:
public class DoubleAdapter extends XmlAdapter<String, Double> {
@Override
public Double unmarshal(String v) throws Exception {
if (v == null || v.isEmpty() || v.equals("null")) {
return null;
}
return Double.parseDouble(v);
}
@Override
public String marshal(Double v) throws Exception {
if (v == null) {
return null;
}
//Edit the format to your needs
return String.format("%.3f", v);
}
}
To use it, simply add the annotation.
@XmlElement(name = "TaxFree")
@XmlJavaTypeAdapter(DoubleAdapter.class)
private double taxFreeValue;
Upvotes: 1
Reputation: 136012
The simplest way is this
double taxFreeValue;
@XmlElement(name = "TaxFree")
private String getTaxFree() {
return String.format("%.3f", taxFreeValue);
}
Note that you can give this method any name and make it private JAXB dont care as soon as the annotation is present.
Upvotes: 5
Reputation: 149007
You can use an XmlAdapter
to convert from the double value to the desired text (String) representation.
Upvotes: 4