Dom4j工具类源码解析
话不多说,上源码:
package com.changeyd.utils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class Dom4jUtils {
public static final String PATH = "src/p1.xml";
// 返回document
public static Document getDocument(String path) {
try {
// 创建解析器
SAXReader saxReader = new SAXReader();
// 得到document
Document document = saxReader.read(path);
return document;
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
// 回写xml的方法
public static void xmlWriters(String path, Document document) {
XMLWriter xmlWriter = null;
try {
OutputFormat format = OutputFormat.createPrettyPrint();
xmlWriter = new XMLWriter(new FileOutputStream(path), format);
try {
xmlWriter.write(document);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
xmlWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
代码简单,供忘记的人复习