黑马程序员技术交流社区
标题:
方老师的xml,用xml做数据库,往里面添加考试信息报异常,我解决不了,大家帮我看下?
[打印本页]
作者:
630681386@qq.co
时间:
2014-3-29 17:49
标题:
方老师的xml,用xml做数据库,往里面添加考试信息报异常,我解决不了,大家帮我看下?
这是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();
}
复制代码
真不知道哪里错了
作者:
刘望望
时间:
2014-3-30 00:13
不知道你XmlUtils类是怎么写的,XmlUtils.getElement().appendChild(elstudent);这里会出现异常,有可能是你XmlUtils类中getDocument方法返回的Document对象和getElement方法使用的Document对象不是同一个。
作者:
630681386@qq.co
时间:
2014-3-30 09:09
明白了,谢谢,说的是有理的,解决了
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2