2

我是 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>
4

3 回答 3

3

以为我已经回答了这个,但是答案消失了...

首先不要这样做:

      } catch (JAXBException e) {
        e.printStackTrace();
      }

您正在捕获异常,将文本转储到标准输出,然后继续,就好像什么都没发生一样。这是IDE添加的无用样板,不要这样做

由于您想根据文件是否已经存在来确定您的行为,因此我建议将块与File.existsif的使用结合使用。

于 2012-11-11T01:21:56.917 回答
2
    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Scanner;

    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.xml.bind.JAXBContext;
    import javax.xml.bind.JAXBException;
    import javax.xml.bind.Marshaller;
    import javax.xml.bind.Unmarshaller;

    public class CoursesApp {

        int choice;
        String courseCode = "", professorName = "", groupIndex = "", classType = "";
        private boolean exists;
        Courselist courselist = new Courselist();
        Course course = new Course();

        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            Courselist courselist = new Courselist();
            Course course = new Course();
            try {

                File file = new File("C:\\Courselist.xml");
                JAXBContext jaxbContext = JAXBContext.newInstance(Courselist.class);

                Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
                courselist = (Courselist) jaxbUnmarshaller.unmarshal(file);
                System.out.println(courselist);

            } catch (JAXBException e) {
                e.printStackTrace();
            }
            //* OVER HERE *//
            CoursesApp ca = new CoursesApp();
            ca.process(0);
        }

        private void process(int choice) {

            //* PRINT MENU *//
            System.out.println("(1) Add a student.\n"
                    + "(2) Add a course.\n"
                    + "(3) Exit.\n");
            System.out.println("Enter the number of your choice: ");
            Scanner sc = new Scanner(System.in);
            choice = sc.nextInt();
            sc.nextLine();
            switch (choice) {
                case 1:
                    //ADD STUDENTS
                    break;
                case 2:
                    File file = new File("C:\\Course.xml");
                    if (file.exists()) {
                        choice = 4;
                        exists = true;
                    } else {
                        System.out.println("File doesnot exist press 4 to create or 3 to exit: ");
                        choice = sc.nextInt();
                        sc.nextLine();
                    }
                    /*ENTER COURSE DETAILS*/
                    if (choice == 4) {
                        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);
                        System.out.println("Are there more records?\n Press 2(yes) or 3(n): ");
                        choice = sc.nextInt();
                        sc.nextLine();
                        if (choice == 3) {
                            /*END OF RECORDS SO GO AHEAD AND UNMARSHAL*/
                            unmarshal(file, courselist);
                        } else {
                            /*ADD MORE COURSE ITEMS*/
                            process(2);
                        }
                    } else {
                        /*FILE NOT EXIST AND USER SELECTED EXIT*/
                        System.exit(0);
                        break;
                    }
                    break;
                case 3:
                    System.exit(0);
                    break;
            }
        }

        private void unmarshal(File file, Courselist courselist) {
            {
                FileWriter fw = null;
                try {
                    JAXBContext jaxbContext =    JAXBContext.newInstance(Courselist.class);
                    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
                    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                    StringBuffer str = new StringBuffer();
                    /*EXISTING FILE SO APPEND*/
                    if (exists) {
                        fw = new FileWriter(file, true);
                        jaxbMarshaller.marshal(courselist, fw);
                    } 
                    /*CREATE NEW FILE*/
                     else {
                        jaxbMarshaller.marshal(courselist, file);
                    }
                    jaxbMarshaller.marshal(courselist, System.out);
                } catch (IOException ex) {
                    Logger.getLogger(CoursesApp.class.getName()).log(Level.SEVERE, null, ex);
                } catch (JAXBException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        fw.close();
                    } catch (IOException ex) {
                        Logger.getLogger(CoursesApp.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
            process(0);//call and print options
        }
    }

这将解决覆盖问题,但您需要一种方法来防止重复 xml 声明。希望这可以帮助

我基本上采用了提问者发布的代码并将代码片段提取到单独的方法中以便更好地理解。我还添加了检查文件是否存在并附加到文件而不是覆盖内容。

Process() 方法用于用户输入和需要执行的操作。在 unmarshal() 中,用户输入绑定到 xml 文件。

于 2012-11-11T02:41:20.627 回答
0

为此,您需要使用 JAXB 2.x Binder抽象。详细教程

于 2012-11-11T01:19:44.817 回答