liuzhen6835
2015-07-09 14:46
采纳率: 51.2%
浏览 2.9k

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 2015-07-09 15:09
    已采纳
    
    
    Element snameEle=rootEle.addElement("sname");
    Element sexEle=rootEle.addElement("sex");
    Element ageEle=rootEle.addElement("age");
    把rootEle换成snoEle
    
    打赏 评论
  • danielinbiti 2015-07-09 15: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");
    
    打赏 评论
  • yuke198907 2015-07-10 00:15

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

    打赏 评论

相关推荐 更多相似问题