1. 程式人生 > >DOM4J解析XML的工具類

DOM4J解析XML的工具類

package cn.tedu.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
/**
 * 解析XML的工具類
 * @author 
 *
 */
public class XMLUtils {
	
	//構造方法私有化,防止類外建立物件
	private XMLUtils() {
	}
	
	/**
	 * 讀取xml並獲取文件物件
	 * @param xmlPath
	 * @return
	 */
	public static Document read(String xmlPath){
		
		Document document = null;
		try {
		//建立解析器
		SAXReader saxReader = new SAXReader();
		//2.獲取xml的文件物件
		document = saxReader.read(xmlPath);
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return document;
	}
	/**
	 * 將document物件寫進xml檔案
	 * @param xmlPath
	 * @param document
	 */
	public static void write(String xmlPath,Document document){
		XMLWriter writer = null;
		try {
			writer = new XMLWriter(new FileOutputStream(new File(xmlPath)),OutputFormat.createPrettyPrint());
			writer.write(document);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(writer!=null){
				try {
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}