File file = new File(request.getSession().getServletContext().getRealPath("/") + "WEB-INF/note.xml");
//注册解析器
SAXBuilder builder = new SAXBuilder();
//读取xml文档
Document doc = builder.build(file);
// 得到根节点
Element root = doc.getRootElement();
//获取子结点集合
List<Element> list = root.getChildren();
boolean isExists = false;
for(Element e:list){
if(idD.equals(e.getAttributeValue("key"))){
//e.removeAttribute("key");
e.setText(note);
isExists = true;
break;
}
}
if(!isExists){
Element entry;
//生成元素
entry = new Element("entry");
//设置各结点的值
entry.setAttribute("key", idD);
entry.setText(note);
System.out.println("root==========="+root);
// 将已经设置好值的entry赋给root
root.addContent(entry);
}
Format format = Format.getCompactFormat();
//设置xml的字符集
format.setEncoding("UTF-8");
//设置xml文件的缩进4个单元格
format.setIndent(" ");
//在元素后换行,每一层元素缩排四格
XMLOutputter XMLOut = new XMLOutputter(format);
try{
//将生成的xml文档Doc输出到c盘的note.xml文档中
XMLOut.output(doc, new FileOutputStream(request.getSession().getServletContext().getRealPath("/") + "WEB-INF/note.xml"));
} catch (FileNotFoundException e) {
// TODO: handle exception
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return NONE;
}