您的位置:首页 > 其它

为xml文件创建一个系统内全局的Document对象,供dom4j进行解析和写操作

2013-03-01 09:39 591 查看
om4j是一个Java的XML API,类似于jdom,用来读写XML文件的。

这是必须使用的jar包, Hibernate用它来读写配置文件。

import java.io.File;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

/**
* 该类负责为xml文件创建一个系统内全局的Document对象,供dom4j进行解析和写操作。
* @author InterdictSky */
public class XmlDocSingleton {

private static Cache documents_cache = CacheManager.getInstance().getCache("org.dom4j.Document");

/**
* 构造一个实例。
*/
public XmlDocSingleton() {
}

/**
* 取得xml文件的Document实例(单例模式)
* @param xml XML文件。
* @return 该xml文件的Document对象。如果为空或者文件不存在,返回NULL
*/
public Document getDocument(File xml){
if(xml ==null || !xml.exists()){
return null;
}
if(documents_cache.isKeyInCache(xml)){
if (documents_cache.get(xml)!=null){
return (Document)documents_cache.get(xml).getValue();
}
}

try {
SAXReader xmlReader = new SAXReader();
Document document = xmlReader.read(xml);
documents_cache.put(new net.sf.ehcache.Element(xml, document));
return document;
} catch (DocumentException ex) {
return ex;        }
return null;
}
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐