使用dom4j读取xml配置文件

来源:互联网 发布:mac钥匙串怎么关闭 编辑:程序博客网 时间:2024/05/17 02:55
实现步骤以及源码:

1、写xml文件读取类读取xml文档内容返回Document对象,此处作为公共xml操作类,用于读取和操作xml文档内容。

package com.ven.util;import java.io.File;import java.io.FileWriter;import java.io.IOException;import java.io.InputStream;import java.io.StringReader;import java.net.URL;import org.apache.log4j.Logger;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 XMLHelper {private static Logger logger=Logger.getLogger(XMLHelper.class);/** * 描述:读取xml文件返回Docment对象 * @author vensins * @created 2017年7月27日 下午5:22:17 * @since  * @param xmlFile * xml文件file对象 * @return */public static Document getDocument(File xmlFile){try {SAXReader saxReader=new SAXReader();return saxReader.read(xmlFile);} catch (DocumentException e) {logger.error("读取xml文件出错,返回nulll",e);return null;}}/** * 描述:读取xml文档返回Document对象 * @author vensins * @created 2017年7月27日 下午5:26:03 * @since  * @param xmlString * xml文档路径 * @return */public static Document getDocument(String xmlString){try {if(xmlString==null||xmlString.equals(""))return null;SAXReader saxReader=new SAXReader();File file=new File(xmlString);return saxReader.read(file);} catch (DocumentException e) {logger.error("读取xml文件失败!",e);return null;}}/** * 描述:读取xml文档内容返回Document对象 * @author vensins * @created 2017年7月27日 下午5:36:02 * @since  * @param xmlString * @return */public static Document getDocumentFromString(String xmlString){try {if(xmlString==null||xmlString.equals(""))return null;SAXReader saxReader=new SAXReader();return saxReader.read(new StringReader(xmlString));} catch (DocumentException e) {// TODO Auto-generated catch blocke.printStackTrace();}return null;}/** * 描述:保存Document文档到文件 * @author vensins * @created 2017年7月27日 下午5:41:24 * @since  * @param document * Document对象 * @param filePath * 保存文件的路径 * @param outputFormat * 保存文件的格式(GBK,UTF-8) * @return */public static boolean saveToFile(Document document,String filePath,OutputFormat outputFormat){XMLWriter writer;File file=new File(filePath);if(!file.exists()){try {file.createNewFile();if(!file.isDirectory())return false;} catch (IOException e) {logger.error("创建文件'"+filePath+"'失败",e);return false;}}try {writer=new XMLWriter(new FileWriter(new File(filePath)));writer.write(document);writer.close();return true;} catch (IOException e) {logger.error("写文件"+filePath+"'出错",e);}return false;}/** * 描述:写入Document对象到xml * @author vensins * @created 2017年7月27日 下午5:38:10 * @since  * @param filePath * @param doc * @return */public static boolean writeToXml(String filePath,Document doc){OutputFormat format=new OutputFormat();format.setEncoding("GBK");if(saveToFile(doc, filePath, format))return true;return false;}/** * 描述:指定位置读取xml文件 * @author vensins * @created 2017年7月27日 下午5:58:13 * @since  * @param cls * @param XmlFile * @return */public static Document getDocument(Class cls,String XmlFile){Document document = null;//装载类的目录ClassLoader loader = cls.getClassLoader();// 先从当前类所处路径的根目录中寻找属性文件File f;//根据文件地址装载文件URL url = loader.getResource(XmlFile);if ( url != null ){    f = new File(url.getPath());    //文件不为空的时候进行读取xml类操作    if ( f != null && f.exists() && f.isFile() )    {    document=XMLHelper.getDocument(f);    }else{    //通过流的形式读取xml文件    InputStream ins=null;    try {        if(loader!=null){        ins=loader.getResourceAsStream(XmlFile);        }        if(ins!=null){        SAXReader saxReader=new SAXReader();document=saxReader.read(ins);        }} catch (DocumentException e) {logger.error("读取xml文件'"+XmlFile+"'失败",e);}finally{try {if(ins!=null){ins.close();ins=null;}} catch (IOException e) {logger.error("",e);}}    }}return document;}}


2、写配置文件公共操作类,用于取配置文件中的配置信息

实现思路:对读取的xml的document对象进行解析,以键值对的形式存入map对象,取配置值时通过键值对(父级配置项目.子级配置项)的形式取出对应的配置信息

package com.ven.util;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import org.apache.log4j.Logger;import org.dom4j.Document;import org.dom4j.Element;public class Configuration {private static Logger logger=Logger.getLogger(Configuration.class);private static String CONFIG_FILE_NAME="resources/configuration.xml";private static Map itemMap=new HashMap();static{load_config();}private static void load_config(){try{Document document = XMLHelper.getDocument(Configuration.class, CONFIG_FILE_NAME);if(document!=null){Element element=document.getRootElement();List catList=element.elements("category");for (Iterator catIter=catList.iterator();catIter.hasNext();) {Element catElement=(Element) catIter.next();String catName=catElement.attributeValue("name");if(catName==null||catName.equals(""))continue;List itemList=catElement.elements("item");for (Iterator itemIter=itemList.iterator();itemIter.hasNext();) {Element itemElement=(Element) itemIter.next();String itemName=itemElement.attributeValue("name");String value=itemElement.attributeValue("value");if (itemName==null||itemName.equals("")) continue;itemMap.put(catName+"."+itemName, value);}}}}catch(Exception ex){logger.error("读取配置文件错误",ex);}}/** * 描述:获取字符串配置值 * @author vensins * @created 2017年7月28日 上午9:33:39 * @since  * @param name * @return */public static String getString(String name){String value=(String) itemMap.get(name);return value==null?"":value;}/** * 描述:获取字符串配置值,为空时取默认值 * @author vensins * @created 2017年7月28日 上午9:36:47 * @since  * @param name * @param defaultValue * @return */public static String getString(String name,String defaultValue){String value=(String) itemMap.get(name);return value==null||value.equals("")?defaultValue:value;}/** * 描述:获取配置文件中的整数项配置 * @author vensins * @created 2017年7月28日 上午9:41:49 * @since  * @param name * @return */public static int getInt(String name){String value=(String) itemMap.get(name);try {return Integer.parseInt(value);} catch (Exception e) {logger.error("配置文件key["+name+"]配置错误,return 0",e);return 0;}}/** * 描述:获取配置文件中的整数项配置,错误是返回默认值 * @author vensins * @created 2017年7月28日 上午9:43:12 * @since  * @param name * @param defaultValue * @return */public static int getInt(String name,int defaultValue){String value=(String) itemMap.get(name);try {return Integer.parseInt(value);} catch (Exception e) {logger.error("配置文件key["+name+"]配置错误,返回默认值"+defaultValue,e);return defaultValue;}}/** * 描述:获取配置文件中的boolean值 * @author vensins * @created 2017年7月28日 上午9:46:29 * @since  * @param name * @return */public static boolean getBoolean(String name){String value=(String) itemMap.get(name);return Boolean.valueOf(value).booleanValue();}/** * 描述:获取配置文件中的Double值 * @author vensins * @created 2017年7月28日 上午9:51:24 * @since  * @param name * @param defaultValue * @return */public static Double getDouble(String name,Double defaultValue) {String value=(String) itemMap.get(name);try {return Double.parseDouble(value);} catch (Exception e) {logger.error("配置文件key["+name+"]配置错误,返回默认值"+defaultValue,e);return defaultValue;}}public static Map getItems(){return itemMap;}}

以下内容为xml文件的内容模板以及使用样例

<?xml version="1.0" encoding="GBK"?><system><category name="article" description="文章配置"><item name="ListPageNum" value="10" description="文章列表页面" /></category><category name="test2" description="配置信息二"><item name="test2-1" value="0" description="" /><item name="test2-2" value="12.4" description="" /><item name="test2-3" value="啊啊啊" description="" /></category></system>


读取时使用Configuration.getString("test1.test1-1")获取 到配置值"1"
读取时使用Configuration.getString("test2.test1-3")获取 到配置值"啊啊啊"

读取时使用Configuration.getString("test2.test1-3")获取 到配置值"啊啊啊"
原创粉丝点击