Java HTML / XML How to - Control JAXB element value field








Question

We would like to know how to control JAXB element value field.

Answer

import java.io.File;
//from w  ww . j  a  v a 2s . c  o m
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

public class Main {

  public static void main(String[] args) throws Exception {
    JAXBContext jc = JAXBContext.newInstance(Property.class);

    Unmarshaller unmarshaller = jc.createUnmarshaller();
    File xml = new File("input.xml");
    Property property = (Property) unmarshaller.unmarshal(xml);

    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(property, System.out);
  }

  @XmlRootElement
  @XmlAccessorType(XmlAccessType.FIELD)
  public static class Property {

    @XmlJavaTypeAdapter(DoubleValueAdapter.class)
    private Double floorArea;

    public double getFloorArea() {
      return floorArea;
    }

    public void setFloorArea(double floorArea) {
      this.floorArea = floorArea;
    }

  }

  public static class DoubleValueAdapter extends
      XmlAdapter<DoubleValueAdapter.AdaptedDoubleValue, Double> {

    public static class AdaptedDoubleValue {
      public double value;
    }

    @Override
    public AdaptedDoubleValue marshal(Double value) throws Exception {
      AdaptedDoubleValue adaptedDoubleValue = new AdaptedDoubleValue();
      adaptedDoubleValue.value = value;
      return adaptedDoubleValue;
    }

    @Override
    public Double unmarshal(AdaptedDoubleValue adaptedDoubleValue)
        throws Exception {
      return adaptedDoubleValue.value;
    }
  }
}

input.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<property>
    <floorArea>
        <value>1.23</value>
    </floorArea>
</property>