Java HTML / XML How to - Create Parent child relation, superclass elements in serialization, in Binding








Question

We would like to know how to create Parent child relation, superclass elements in serialization, in Binding.

Answer

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlType;
/*w  w w  . ja va  2 s.  c  o  m*/
public class Main {

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

    Child child = new Child();
    child.setParentProp("parent-value");
    child.setChildProp("child-value");

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

  @XmlRootElement
  @XmlType(propOrder = { "childProp", "parentProp" })
  public static class Child extends Parent {

    private String childProp;

    public String getChildProp() {
      return childProp;
    }

    public void setChildProp(String childProp) {
      this.childProp = childProp;
    }

  }

  @XmlTransient
  public static abstract class Parent {

    private String parentProp;

    public String getParentProp() {
      return parentProp;
    }

    public void setParentProp(String parentProp) {
      this.parentProp = parentProp;
    }

  }
}