JAXB

JAXB - Java Architecture for XML Binding
JAXB提供了一种把Java object转成XML,或者把XML转成Java object的机制。

JAXB有两个过程,一个是unmarshalling,另一个是marshalling。
unmarshalling:reading。从XML instance转成Java content。
marshalling:writing。从Java content转成XML instance。


JAXB

Marshalling
如果想把Java objects转成XML document,我们需要一个POJO class。如下:

import javax.xml.bind.annotation.*;

@XmlRootElement
public class Student {
    private String name;
    private String subject;
    private int id;
    Student() {
    }
    Student(String name, int id, String subject) {
        this.name = name;
        this.id = id;
        this.subject = subject;
    }
    @XmlElement
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @XmlAttribute
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    @XmlElement
    public String getSubject() {
        return subject;
    }
    public void setSubject(String subject) {
        this.subject = subject;
    }
}

在这里面:

  • @XmlRootElement 指定了XML document的root element。
  • @XmlAttribute 指定了root element的attribute。
  • @XmlElement 指定了root element的sub-element。

然后我们实际的使用marshaller method:

try {
    // creating the JAXB context
    JAXBContext jContext = JAXBContext.newInstance(Student.class);
    // creating the marshaller object
    Marshaller marshallObj = jContext.createMarshaller();
    // setting the property to show xml format output
    marshallObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    // setting the values in POJO class
    Student student = new Student(“abc”, 123, “hadoop”);
    // calling the marshall method
    marshallObj.marshal(student, new FileOutputStream(“/home/coding/Desktop/student.xml”));
} catch(Exception e) {
    e.printStackTrace();
}

生成的XML像如下:



    abc
    hadoop

Unmarshalling

try {
    // getting the xml file to read
    File file = new File(“/home/coding/Desktop/student.xml”);
    // creating the JAXB context
    JAXBContext jContext = JAXBContext.newInstance(Student.class);
    // creating the unmarshall object
    Unmarshaller unmarshallerObj = jContext.createUnmarshaller();
    // calling the unmarshall method
    Student student = (Student) unmarshallerObj.unmarshal(file);
    System.out.println(student.getName()+” “+student.getId()+” “+student.getSubject());
} catch(Exception e) {
    e.printStackTrace();
}

你可能感兴趣的:(JAXB)