我是 JAXB 的新手,所以请在您的评论中宽容!无论如何,每次运行我想要的程序时,我都面临着现有 xml 文件被覆盖的问题。假设添加到现有的 xml。请帮忙!
CoursesApp.java:
package Courses;
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
public class CoursesApp {
public static void main(String[] args) {
int choice;
String courseCode = "", professorName = "", groupIndex = "", classType = "";
Scanner sc = new Scanner(System.in);
try {
File file = new File("C:\\Courselist.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Courselist.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Courselist courselist = (Courselist) jaxbUnmarshaller.unmarshal(file);
System.out.println(courselist.course.get(0).getclassType());
} catch (JAXBException e) {
e.printStackTrace();
}
Courselist courselist = new Courselist();
Course course = new Course();
do{
System.out.println("(1) Add a student.\n" +
"(2) Add a course.\n" +
"(3) Exit.\n");
System.out.print("Enter the number of your choice: ");
choice = sc.nextInt();
sc.nextLine();
switch (choice) {
case 1:
break;
case 2:
System.out.println("Please enter course code:");
courseCode = sc.nextLine();
System.out.println("Please enter class type:");
classType = sc.nextLine();
System.out.println("Please enter group index:");
groupIndex = sc.nextLine();
System.out.println("Please enter professor name:");
professorName = sc.nextLine();
course.setcourseCode(courseCode);
course.setclassType(classType);
course.setgroupIndex(groupIndex);
course.setprofessor(professorName);
courselist.course.add(course);
try{
File file = new File("C:\\Courselist.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Courselist.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(courselist, file);
jaxbMarshaller.marshal(courselist, System.out);
}catch(JAXBException e)
{
e.printStackTrace();
}
break;
case 3: //Modify course
break;
default: System.out.println("Please enter a number between 1-3.\n");
break;
}
} while (choice!=3);
}
}
课程列表.xml:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<courselist>
<course>
<classType>lect</classType>
<courseCode>2002</courseCode>
<groupIndex>12</groupIndex>
<professor>james</professor>
</course>
</courselist>
如果我添加另一门课程,则添加到以下课程:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<courselist>
<course>
<classType>lect</classType>
<courseCode>2002</courseCode>
<groupIndex>12</groupIndex>
<professor>james</professor>
</course>
<course>
<classType>Lab</classType>
<courseCode>2001</courseCode>
<groupIndex>1</groupIndex>
<professor>john</professor>
</course>
</courselist>