import javax.xml.bind.*;
import java.io.File;
public class Main {
public static void main(String[] args) throws JAXBException {
Student student = new Student("John", 21);
JAXBContext context = JAXBContext.newInstance(Student.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(student, new File("student.xml"));
Unmarshaller unmarshaller = context.createUnmarshaller();
Student parsedStudent = (Student) unmarshaller.unmarshal(new File("student.xml"));
System.out.println(parsedStudent.getName());
System.out.println(parsedStudent.getAge());
}
}
@XmlRootElement
class Student {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@XmlElement
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlElement
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}