App下載
首頁javajaxbJava HTML/XML - 如何使用JaxB綁定類層次結(jié)構(gòu)

Java HTML/XML - 如何使用JaxB綁定類層次結(jié)構(gòu)

我們想知道如何使用JaxB綁定類層次結(jié)構(gòu)。
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

public class Main {

  public static void main(String[] args) throws Exception {
    JAXBContext jc = JAXBContext.newInstance(A.class, B.class);
    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    A a = new A();
    a.setFoo("Hello World");
    marshaller.marshal(a, System.out);

    B b = new B();
    b.setFoo("Hello World");
    marshaller.marshal(b, System.out);
  }

  @XmlRootElement
  public static class A implements IntF {

    private String foo;

    @Override
    @XmlElement(name = "renamed-foo")
    public String getFoo() {
      return foo;
    }

    @Override
    public void setFoo(String foo) {
      this.foo = foo;
    }

  }

  @XmlRootElement
  public static class B implements IntF {

    private String foo;

    @Override
    @XmlAttribute
    public String getFoo() {
      return foo;
    }

    @Override
    public void setFoo(String foo) {
      this.foo = foo;
    }

  }

  public interface IntF {
    public String getFoo();

    public void setFoo(String foo);
  }
}