dom4j之小小工具

dom4j经常不用,方法忘了又记,故做出读取xml和把document写入xml的小小工具~~~

/**
 * 读取document和将document对象写入到xml的小工具
 * 使用该类必须给出dom4j的jar包
 * @author hui.zhang
 *
 */
public class Dom4jUtils {
    private Dom4jUtils() {}
    /**
     * 通过路径获取document对象
     * @param pathname xml的路径
     * @return 返回document对象
     * @throws DocumentException
     */
    public static Document getDocument(File pathname) throws DocumentException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(pathname);
        return document;
    }
    
    /**
     * 传一个document对象写入到指定xml路径下
     * @param path 写回路径
     * @param document 传一个document对象
     * @throws IOException
     */
   public static void write2XML(File path, Document document) throws IOException {
        OutputFormat format = OutputFormat.createPrettyPrint();
        //format.setEncoding("UTF-8");//默认的编码就是UTF-8
        XMLWriter xml = new XMLWriter(new FileOutputStream(path), format);
        xml.write(document);
    }
    
}
原文地址:https://www.cnblogs.com/stefan95/p/7585738.html