dom4j 写入已经有内容的xml文件,会覆盖到原来的 内容

SupMrK 发布于 2015/04/14 13:31
阅读 2K+
收藏 0

第一次

package com.hebut.student.xmldao;


import java.io.File;
import java.io.FileWriter;
import java.io.IOException;


import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;


import com.hebut.student.pojo.Student;


public class WriteXml {


static String filepath="student.xml";




public static boolean write(Student stu){


File file=new File(filepath);
if(!file.isFile()){
try {
file.createNewFile();
OutputFormat format=OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");
XMLWriter write = new XMLWriter(new FileWriter(file), format);
Document doc=DocumentHelper.createDocument();
Element students=doc.addElement("students");
Element student =students.addElement("student");
student.addAttribute("id","001");
Element name=student.addElement("name");
name.setText(stu.getName());
Element age =student.addElement("age");
age.setText(String.valueOf(stu.getAge()));
Element pass=student.addElement("pass");
pass.setText(stu.getPass());
Element sex =student.addElement("sex");
sex.setText(stu.getSex());
Element grade =student.addElement("grade");
grade.setText(stu.getGrade());
Element phone =student.addElement("phone");
phone.setText(stu.getPhone());
Element address =student.addElement("address");
address.setText(stu.getAddress());
try {
write.write(doc);
write.flush();
write.close();
} catch (IOException e) {
return false;
}


return true;
} catch (IOException e) {
System.out.println("write xmlfile error");
return false;
}
}


SAXReader reader=new SAXReader();
try {
OutputFormat format=OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");
XMLWriter write = new XMLWriter(new FileWriter(new File(filepath)), format);


//
Document doc = reader.read(new File(filepath));
// Element students=DocumentHelper.createElement("students");
Element root=doc.getRootElement();
Element student =root.addElement("student");
Element name=student.addElement("name");
name.setText(stu.getName());
Element age =student.addElement("age");
age.setText(String.valueOf(stu.getAge()));
Element pass=student.addElement("pass");
pass.setText(stu.getPass());
Element sex =student.addElement("sex");
sex.setText(stu.getSex());


Element grade =student.addElement("grade");


grade.setText(stu.getGrade());
Element phone =student.addElement("phone");
phone.setText(stu.getPhone());
Element address =student.addElement("address");
address.setText(stu.getAddress());

write.write(doc);
write.close();
} catch (DocumentException e1) {
return false;
} catch(Exception e){
return false;
}
return true;




}


}

文件不存在时,可以通过第一种方法写入xml文件,当文件存在时,执行下面的代码,输入的内容会被覆盖

Document doc = reader.read(new File(filepath));//会出现异常


加载中
0
LC
LC
dom4j没有appendable的方法么
0
_
__暗白。
你的意思是写入重复的element时会覆盖?
0
_
__暗白。

按照你给的代码,不会覆盖之前生成的student节点,每次都会生成一个新的student节点。而且是累加的


返回顶部
顶部