2 liuzhen6835 liuzhen6835 于 2015.07.09 22:46 提问

dom4j向xml文件中增加数据后缺少结尾标签

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>

3个回答

liuzhen6835
liuzhen6835   2015.07.09 23:09
已采纳


Element snameEle=rootEle.addElement("sname");
Element sexEle=rootEle.addElement("sex");
Element ageEle=rootEle.addElement("age");
把rootEle换成snoEle
danielinbiti
danielinbiti   Ds   Rxr 2015.07.09 23:09
 Element snoEle=rootEle.addElement("student");
Element snameEle=rootEle.addElement("sname");
Element sexEle=rootEle.addElement("sex");
Element ageEle=rootEle.addElement("age");

改成
Element snoEle=rootEle.addElement("student");
Element snameEle=snoEle.addElement("sname");
Element sexEle=snoEle.addElement("sex");
Element ageEle=snoEle.addElement("age");
liuzhen6835
liuzhen6835 不好意思啊!当我检查出错误提交了,刷新才看到你的。还望你不要放在心上,以后还望多多帮忙
2 年多之前 回复
yuke198907
yuke198907   2015.07.10 08:15

这个不就是包含开始结束了么

Csdn user default icon
上传中...
上传图片
插入图片