The following example shows serializing a POJO with multiple lists to an XML.
The POJO should have a no-arg default constructor and
@XmlRootElement annotation at class level.
The annotation @XmlElementWrapper allows us to
provide a wrapper tag name around list of elements.
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD) //Allows to get data through fields rather than public getter/setters public class StudentClass {
private String name;
@XmlElementWrapper(name = "subjects_list")
@XmlElement(name="subject") private List<String> subjects = new ArrayList<String>();
@XmlElementWrapper(name = "student_list")
@XmlElement(name="student") private List<Student> students = new ArrayList<Student>();
public StudentClass() {
}
public StudentClass(String name) { super(); this.name = name;
} public String getName() { return name;
} public void setName(String name) { this.name = name;
}
public List<Student> getStudents() { return students;
} public void setStudents(List<Student> students) { this.students = students;
}
public List<String> getSubjects() { return subjects;
}
public void setSubject(List<String> subjects) { this.subjects = subjects;
}
public static void main (String [] args) throws JAXBException {
Student student = new Student("Sriram", "Kasireddi", 2, "Painting", new Date());
Student student2 = new Student("Sudhakar", "Kasireddi", 26, "Coding", new Date());
StudentClass stdCls = new StudentClass("MPC");
stdCls.getSubjects().addAll(Arrays.asList("Maths", "Physics", "Chemistry"));
stdCls.getStudents().addAll(Arrays.asList(student, student2));
/**
* Create JAXB Context from the classes to be serialized
*/
JAXBContext context = JAXBContext.newInstance(StudentClass.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.marshal(stdCls, System.out);