Java HTML / XML How to - Marshall/ and unMarshall








Question

We would like to know how to Marshall/ and unMarshall.

Answer

//from w  w w  .j  a v a2  s  .c  om
import java.io.File;
import java.util.List;

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.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "DataSet")
@XmlAccessorType(XmlAccessType.FIELD)
class DataSet {

  @XmlElement(name = "WeekNumber")
  private int weekNumber;

  @XmlElementWrapper(name = "EmployeeRatesLevelA")
  @XmlElement(name = "Rate")
  private List<Float> employeeRatesLevelA;

  @XmlElementWrapper(name = "EmployeeRatesLevelB")
  @XmlElement(name = "Rate")
  private List<Float> employeeRatesLevelB;

}

public class Main {

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

    Unmarshaller unmarshaller = jc.createUnmarshaller();
    File xml = new File("input.xml");
    DataSet dataSet = (DataSet) unmarshaller.unmarshal(xml);

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

}