8

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?

Juraj Ćutić
  • 206
  • 2
  • 10

3 Answers3

5

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.

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • Worked for me, if anyone has problems, make sure to check the `@XmlAccessorType` of your class. I have it on `@XmlAccessorType(XmlAccessType.NONE)` so marshalling that it only takes into account `@XmlElement` annotations. – Touniouk Jul 10 '20 at 03:05
4

You can use an XmlAdapter to convert from the double value to the desired text (String) representation.

Community
  • 1
  • 1
bdoughan
  • 147,609
  • 23
  • 300
  • 400
1

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;
Quoc Tran
  • 11
  • 2