首页javajaxbJava HTML/XML - 如何控制JAXB元素值字段

Java HTML/XML - 如何控制JAXB元素值字段

我们想知道如何控制JAXB元素值字段。
import java.io.File;

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;
    }
  }
}