使用dom4j读取xml配置文件

文章来源:乐窝小站(https://www.mrven.top/archives/19.html)

实现步骤以及源码:

 

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 block
			e.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")获取 到配置值"啊啊啊"

 

文章来源:乐窝小站(https://www.mrven.top/archives/19.html)

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值