首页javajaxbJava HTML/XML - 如何在Binding中创建父子关系,序列化中的超类元素

Java HTML/XML - 如何在Binding中创建父子关系,序列化中的超类元素

我们想知道如何在Binding中创建父子关系,序列化中的超类元素。
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;

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

  }
}