这是xml- <?xml version="1.0" encoding="UTF-8" standalone="no"?>
- <exam>
- <student examid="222" idcard="111">
- <name>张三</name>
- <location>襄阳</location>
- <score>78</score>
- </student>
-
- <student examid="555" idcard="333">
- <name>李四</name>
- <location>襄阳</location>
- <score>65</score>
- </student>
- </exam>
复制代码
StudentDAO中的add方法- //向xml中添加数据
- public static void add(Student stu)
- {
-
- try {
- Document docu = XmlUtils.getDocument();
- //得到Document对象
- Element elstudent = docu.createElement("student");//创建节点并添加属性
- elstudent.setAttribute("idcard", stu.getIdcard());
- elstudent.setAttribute("examid", stu.getExamid());
- //创建子节点,并设计值
- Element name = docu.createElement("name");
- name.setTextContent(stu.getName());
- Element location = docu.createElement("location");
- location.setTextContent(stu.getLocation());
- Element score = docu.createElement("score");
- score.setTextContent(stu.getScore());
- //将子节点添加到父节点中
- elstudent.appendChild(name);
- elstudent.appendChild(location);
- elstudent.appendChild(score);
-
- //在根节点上挂就是appendchild抛的异常DOMException
- XmlUtils.getElement().appendChild(elstudent);
-
- XmlUtils.Write2Xml(docu);//将内存中的数据写入到xml中
- } catch (Exception e) {
- throw new RuntimeException(e);//将编译事异常转换为运行时异常
- }
-
- }
复制代码
Test中的添加方法:- Scanner sc=new Scanner(System.in);
- System.out.println("请输入学生姓名:");
- String name=sc.nextLine();
- System.out.println("请输入学生身份证号码:");
- String idcard=sc.nextLine();
- System.out.println("请输入学生准考证号码:");
- String examid=sc.nextLine();
- System.out.println("请输入学生所在地:");
- String location=sc.nextLine();
- System.out.println("请输入学生成绩:");
- String score=sc.nextLine();
- Student stu=new Student(idcard, examid, name, location, score);
-
- try {
- StudentDAO.add(stu);
- } catch (Exception e) {
- e.printStackTrace();
- }
复制代码
真不知道哪里错了 |