public class LogWriter {
private static final String PATH = "e://log.xml";
/**
* 写入log.xml
*
* @param st
* 执行action前时间
* @param et
* 执行action后时间
* @param ac
* action类名
* @param res
* 执行结果result
*/
public void log(String st, String et, String ac, String res) {
SAXReader reader = new SAXReader();
try {
File logXML = new File(PATH);
Document doc;
Element root;
if (logXML.exists()) {
doc = reader.read(new File(PATH));
root = doc.getRootElement();
}else {//不存在log.xml
doc = DocumentHelper.createDocument();
root = doc.addElement("log");
}
Element action = root.addElement("action");
Element name = action.addElement("name");
name.setText(ac);
Element stime = action.addElement("s-time");
stime.setText(st);
Element etime = action.addElement("e-time");
etime.setText(et);
Element result = action.addElement("result");
result.setText(res);
writeXML(doc);
} catch (DocumentException e) {
e.printStackTrace();
}
}
/**
* 将修改的log.xml写入磁盘
*
* @param doc
* 修改过的log.xml文件
*/
private void writeXML(Document doc) {
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");
XMLWriter writer = null;
try {
writer = new XMLWriter(new FileWriter(new File(PATH)), format);
doc.normalize();
writer.write(doc);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
dom4j 修改xml并写入磁盘
最新推荐文章于 2024-04-05 15:52:44 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)