Serialize and DeSerialize Object List in JAXB

Create new package, named demo. In this package, create new java class, named Main as below

package demo;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import entities.Student;
import entities.Students;

public class Main {

	private static void serialize(Students students, String xmlFile) {
		try {
			JAXBContext jaxbContext = JAXBContext.newInstance(Students.class);
			Marshaller marshaller = jaxbContext.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			// Display result to console
			marshaller.marshal(students, System.out);
			// Save result to xml file
			marshaller.marshal(students, new File(xmlFile));
		} catch (Exception e) {
			System.err.println(e.getMessage());
		}
	}

	private static void deSerialize(String xmlFile) {
		try {
			JAXBContext jaxbContext = JAXBContext.newInstance(Students.class);
			Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
			Students students = (Students) unmarshaller.unmarshal(new File(xmlFile));
			System.out.println("Student List");
			for (Student student : students.getStudents()) {
				System.out.println("Id: " + student.getId());
				System.out.println("Name: " + student.getName());
				System.out.println("Age: " + student.getAge());
				System.out.println("Score: " + student.getScore());
				System.out.println("==========================");
			}
		} catch (Exception e) {
			System.err.println(e.getMessage());
		}
	}

	public static void main(String[] args) {

		String xmlFile = "src\\data\\students.xml";
		Students students = new Students();
		List<Student> list = new ArrayList<Student>();
		list.add(new Student("st01", "name 1", 20, 6.7));
		list.add(new Student("st02", "name 2", 19, 7.8));
		list.add(new Student("st03", "name 3", 22, 8.0));
		students.setStudents(list);
		serialize(students, xmlFile);
		deSerialize(xmlFile);

	}

}




<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<students>
    <student>
        <id>st01</id>
        <name>name 1</name>
        <age>20</age>
        <score>6.7</score>
    </student>
    <student>
        <id>st02</id>
        <name>name 2</name>
        <age>19</age>
        <score>7.8</score>
    </student>
    <student>
        <id>st03</id>
        <name>name 3</name>
        <age>22</age>
        <score>8.0</score>
    </student>
</students>

Student List
Id: st01
Name: name 1
Age: 20
Score: 6.7
==========================
Id: st02
Name: name 2
Age: 19
Score: 7.8
==========================
Id: st03
Name: name 3
Age: 22
Score: 8.0
==========================