Java HTML / XML How to - Use @XmlElements to mark with @XmlJavaTypeAdapters








Question

We would like to know how to use @XmlElements to mark with @XmlJavaTypeAdapters.

Answer

import java.io.File;
import java.io.Serializable;
import java.util.List;
/*from  w w w.  ja v  a  2  s .c  om*/
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.XmlElements;
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(Compound.class);

    Unmarshaller unmarshaller = jc.createUnmarshaller();
    Compound compound = (Compound) unmarshaller
        .unmarshal(new File("input.xml"));
    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(compound, System.out);
  }

  public static abstract class Value implements Serializable {
  }

  public static class SimpleAdapter extends XmlAdapter<String, Simple> {

    @Override
    public Simple unmarshal(String v) throws Exception {
      Simple simple = new Simple();
      simple.setSimple(v);
      return simple;
    }

    @Override
    public String marshal(Simple v) throws Exception {
      return v.getSimple();
    }

  }

  @XmlRootElement(name = "compound")
  @XmlAccessorType(XmlAccessType.FIELD)
  public static class Compound extends Value {
    @XmlElements({ @XmlElement(name = "simple", type = Simple.class),
        @XmlElement(name = "compound", type = Compound.class) })
    protected List<Value> value;

    public List<Value> getValue() {
      return value;
    }

    public void setValue(List<Value> value) {
      this.value = value;
    }

  }

  @XmlJavaTypeAdapter(SimpleAdapter.class)
  public static class Simple extends Value {
    private java.lang.String simple;

    public java.lang.String getSimple() {
      return simple;
    }

    public void setSimple(java.lang.String simple) {
      this.simple = simple;
    }

  }

}

input.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<compound>
    <simple>
        <simple>FOO</simple>
    </simple>
    <compound/>
</compound>