public boolean insertStudent(Student student)
{
boolean flag=false;
SAXReader saxReader=new SAXReader();
try {
Document doc=saxReader.read(new File("db\student.xml"));
Element rootEle=doc.getRootElement();
Element snoEle=rootEle.addElement("student");
Element snameEle=rootEle.addElement("sname");
Element sexEle=rootEle.addElement("sex");
Element ageEle=rootEle.addElement("age");
snoEle.addAttribute("sno", student.getSno());
snameEle.setText(student.getSname());
sexEle.setText(student.getSex());
ageEle.setText(String.valueOf(student.getAge()));
OutputFormat of=OutputFormat.createPrettyPrint();
of.setEncoding("GBK");
XMLWriter xWrite=new XMLWriter(new FileWriter("db\student.xml"),of);
xWrite.write(doc);
xWrite.close();
flag=true;
}
catch (DocumentException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return flag;
}
插入数据后打开xml其中的数据是:
<student sno="1006"/>
<sname>lz</sname>
<sex>lz</sex>
<age>32</age>
<student sno="1007"/>
<sname>hehe</sname>
<sex>he</sex>
<age>32</age>
<student sno="1008"/>
<sname>haha</sname>
<sex>ha</sex>
<age>32</age>
都没有</student>