怎么用dom4j读取xml配置文件

发布时间:2021-08-16 18:17:26 作者:chen
来源:亿速云 阅读:143

本篇内容主要讲解“怎么用dom4j读取xml配置文件”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“怎么用dom4j读取xml配置文件”吧!

实现步骤以及源码:
1、写xml文件读取类读取xml文档内容返回Document对象,此处作为公共xml操作类,用于读取和操作xml文档内容。

            点击(此处)折叠或打开

  1. package util;


  2. import java.io.File;

  3. import java.io.FileWriter;

  4. import java.io.IOException;

  5. import java.io.InputStream;

  6. import java.io.StringReader;

  7. import java.net.URL;


  8. import org.apache.log4j.Logger;

  9. import org.dom4j.Document;

  10. import org.dom4j.DocumentException;

  11. import org.dom4j.io.OutputFormat;

  12. import org.dom4j.io.SAXReader;

  13. import org.dom4j.io.XMLWriter;


  14. public class XMLHelper {

  15.                     private static Logger logger=Logger.getLogger(XMLHelper.class);

  16.                     

  17.                     /**

  18.                      * 描述:读取xml文件返回Docment对象

  19.                      * @author vensins

  20.                      * @created 2017年7月27日 下午5:22:17

  21.                      * @since

  22.                      * @param xmlFile

  23.                      *         xml文件file对象

  24.                      * @return

  25.                      */

  26.                     public static Document getDocument(File xmlFile){

  27.                         try {

  28.                             SAXReader saxReader=new SAXReader();

  29.                             return saxReader.read(xmlFile);

  30.                         } catch (DocumentException e) {

  31.                             logger.error("读取xml文件出错,返回nulll",e);

  32.                             return null;

  33.                         }

  34.                     }

  35.                     /**

  36.                      * 描述:读取xml文档返回Document对象

  37.                      * @author vensins

  38.                      * @created 2017年7月27日 下午5:26:03

  39.                      * @since

  40.                      * @param xmlString

  41.                      *         xml文档路径

  42.                      * @return

  43.                      */

  44.                     public static Document getDocument(String xmlString){

  45.                         try {

  46.                             if(xmlString==null||xmlString.equals(""))

  47.                                 return null;

  48.                             SAXReader saxReader=new SAXReader();

  49.                             File file=new File(xmlString);

  50.                             return saxReader.read(file);

  51.                         } catch (DocumentException e) {

  52.                             logger.error("读取xml文件失败!",e);

  53.                             return null;

  54.                         }

  55.                     }

  56.                     /**

  57.                      * 描述:读取xml文档内容返回Document对象

  58.                      * @author vensins

  59.                      * @created 2017年7月27日 下午5:36:02

  60.                      * @since

  61.                      * @param xmlString

  62.                      * @return

  63.                      */

  64.                     public static Document getDocumentFromString(String xmlString){

  65.                         try {

  66.                             if(xmlString==null||xmlString.equals(""))

  67.                                 return null;

  68.                             SAXReader saxReader=new SAXReader();

  69.                             return saxReader.read(new StringReader(xmlString));

  70.                         } catch (DocumentException e) {

  71.                             // TODO Auto-generated catch block

  72.                             e.printStackTrace();

  73.                         }

  74.                         return null;

  75.                     }

  76.                     

  77.                     /**

  78.                      * 描述:保存Document文档到文件

  79.                      * @author vensins

  80.                      * @created 2017年7月27日 下午5:41:24

  81.                      * @since

  82.                      * @param document

  83.                      *         Document对象

  84.                      * @param filePath

  85.                      *         保存文件的路径

  86.                      * @param outputFormat

  87.                      *         保存文件的格式(GBK,UTF-8)

  88.                      * @return

  89.                      */

  90.                     public static boolean saveToFile(Document document,String filePath,OutputFormat outputFormat){

  91.                         XMLWriter writer;

  92.                         File file=new File(filePath);

  93.                         if(!file.exists()){

  94.                             try {

  95.                                 file.createNewFile();

  96.                                 if(!file.isDirectory())

  97.                                     return false;

  98.                             } catch (IOException e) {

  99.                                 logger.error("创建文件'"+filePath+"'失败",e);

  100.                                 return false;

  101.                             }

  102.                         }

  103.                         try {

  104.                             writer=new XMLWriter(new FileWriter(new File(filePath)));

  105.                             writer.write(document);

  106.                             writer.close();

  107.                             return true;

  108.                         } catch (IOException e) {

  109.                             logger.error("写文件"+filePath+"'出错",e);

  110.                         }

  111.                         return false;

  112.                         

  113.                     }

  114.                     /**

  115.                      * 描述:写入DOcument对象到xml

  116.                      * @author vensins

  117.                      * @created 2017年7月27日 下午5:38:10

  118.                      * @since

  119.                      * @param filePath

  120.                      * @param doc

  121.                      * @return

  122.                      */

  123.                     public static boolean writeToXml(String filePath,Document doc){

  124.                         OutputFormat format=new OutputFormat();

  125.                         format.setEncoding("GBK");

  126.                         if(saveToFile(doc, filePath, format))

  127.                             return true;

  128.                         return false;

  129.                     }

  130.                     

  131.                     /**

  132.                      * 描述:指定位置读取xml文件

  133.                      * @author vensins

  134.                      * @created 2017年7月27日 下午5:58:13

  135.                      * @since

  136.                      * @param cls

  137.                      * @param XmlFile

  138.                      * @return

  139.                      */

  140.                     public static Document getDocument(Class cls,String XmlFile){

  141.                         Document document = null;

  142.                         ClassLoader loader = cls.getClassLoader();

  143.                         // 先从当前类所处路径的根目录中寻找属性文件

  144.                         File f;

  145.                         URL url = loader.getResource(XmlFile);

  146.                         if ( url != null )

  147.                         {

  148.                             f = new File(url.getPath());

  149.                          if ( f != null && f.exists() && f.isFile() )

  150.                          {

  151.                                 document=XMLHelper.getDocument(f);

  152.                          }else{

  153.                                 InputStream ins=null;

  154.                                 try {

  155.                                     if(loader!=null){

  156.                                         ins=loader.getResourceAsStream(XmlFile);

  157.                                     }

  158.                                     if(ins!=null){

  159.                                         SAXReader saxReader=new SAXReader();

  160.                                             document=saxReader.read(ins);

  161.                                     }

  162.                                 } catch (DocumentException e) {

  163.                                     logger.error("读取xml文件'"+XmlFile+"'失败",e);

  164.                                 }finally{

  165.                                     try {

  166.                                         if(ins!=null){

  167.                                             ins.close();

  168.                                             ins=null;

  169.                                         }

  170.                                     } catch (IOException e) {

  171.                                         logger.error("",e);

  172.                                     }

  173.                                 }

  174.                          }

  175.                         }

  176.                         return document;

  177.                         

  178.                     }

  179. }

2、写配置文件公共操作类,用于取配置文件中的配置信息
实现思路:对读取的xml的document对象进行解析,以键值对的形式存入map对象,取配置值时通过键值对(父级配置项目.子级配置项)的形式取出对应的配置信息

            点击(此处)折叠或打开

  1. package util;


  2. import java.util.HashMap;

  3. import java.util.Iterator;

  4. import java.util.List;

  5. import java.util.Map;


  6. import org.apache.log4j.Logger;

  7. import org.dom4j.Document;

  8. import org.dom4j.Element;


  9. public class Configuration {

  10.                     

  11.                     private static Logger logger=Logger.getLogger(Configuration.class);

  12.                     private static String CONFIG_FILE_NAME="conf/configuration.xml";

  13.                     

  14.                     private static Map itemMap=new HashMap();

  15.                     static{

  16.                         load_config();

  17.                     }

  18.                     private static void load_config(){

  19.                         try{

  20.                             Document document = XMLHelper.getDocument(Configuration.class, CONFIG_FILE_NAME);

  21.                             if(document!=null){

  22.                                 Element element=document.getRootElement();

  23.                                 List catList=element.elements("category");

  24.                                 for (Iterator catIter=catList.iterator();catIter.hasNext();) {

  25.                                     Element catElement=(Element) catIter.next();

  26.                                     String catName=catElement.attributeValue("name");

  27.                                     if(catName==null||catName.equals(""))

  28.                                         continue;

  29.                                     List itemList=catElement.elements("item");

  30.                                     for (Iterator itemIter=itemList.iterator();itemIter.hasNext();) {

  31.                                         Element itemElement=(Element) itemIter.next();

  32.                                         String itemName=itemElement.attributeValue("name");

  33.                                         String value=itemElement.attributeValue("value");

  34.                                         if (itemName==null||itemName.equals(""))

  35.                                             continue;

  36.                                         itemMap.put(catName+"."+itemName, value);

  37.                                     }

  38.                                 }

  39.                             }

  40.                         }catch(Exception ex){

  41.                             logger.error("读取配置文件错误",ex);

  42.                         }

  43.                     }

  44.                     /**

  45.                      * 描述:获取字符串配置值

  46.                      * @author vensins

  47.                      * @created 2017年7月28日 上午9:33:39

  48.                      * @since

  49.                      * @param name

  50.                      * @return

  51.                      */

  52.                     public static String getString(String name){

  53.                         String value=(String) itemMap.get(name);

  54.                         return value==null?"":value;

  55.                     }

  56.                     /**

  57.                      * 描述:获取字符串配置值,为空时取默认值

  58.                      * @author vensins

  59.                      * @created 2017年7月28日 上午9:36:47

  60.                      * @since

  61.                      * @param name

  62.                      * @param defaultValue

  63.                      * @return

  64.                      */

  65.                     public static String getString(String name,String defaultValue){

  66.                         String value=(String) itemMap.get(name);

  67.                         return value==null||value.equals("")?defaultValue:value;

  68.                     }

  69.                     /**

  70.                      * 描述:获取配置文件中的整数项配置

  71.                      * @author vensins

  72.                      * @created 2017年7月28日 上午9:41:49

  73.                      * @since

  74.                      * @param name

  75.                      * @return

  76.                      */

  77.                     public static int getInt(String name){

  78.                         String value=(String) itemMap.get(name);

  79.                         try {

  80.                             return Integer.parseInt(value);

  81.                         } catch (Exception e) {

  82.                             logger.error("配置文件key["+name+"]配置错误,return 0",e);

  83.                             return 0;

  84.                         }

  85.                     }

  86.                     /**

  87.                      * 描述:获取配置文件中的整数项配置,错误是返回默认值

  88.                      * @author vensins

  89.                      * @created 2017年7月28日 上午9:43:12

  90.                      * @since

  91.                      * @param name

  92.                      * @param defaultValue

  93.                      * @return

  94.                      */

  95.                     public static int getInt(String name,int defaultValue){

  96.                         String value=(String) itemMap.get(name);

  97.                         try {

  98.                             return Integer.parseInt(value);

  99.                         } catch (Exception e) {

  100.                             logger.error("配置文件key["+name+"]配置错误,返回默认值"+defaultValue,e);

  101.                             return defaultValue;

  102.                         }

  103.                     }

  104.                     /**

  105.                      * 描述:获取配置文件中的boolean值

  106.                      * @author vensins

  107.                      * @created 2017年7月28日 上午9:46:29

  108.                      * @since

  109.                      * @param name

  110.                      * @return

  111.                      */

  112.                     public static boolean getBoolean(String name){

  113.                         String value=(String) itemMap.get(name);

  114.                         return Boolean.valueOf(value).booleanValue();

  115.                     }

  116.                     /**

  117.                      * 描述:获取配置文件中的Double值

  118.                      * @author vensins

  119.                      * @created 2017年7月28日 上午9:51:24

  120.                      * @since

  121.                      * @param name

  122.                      * @param defaultValue

  123.                      * @return

  124.                      */

  125.                     public static Double getDouble(String name,Double defaultValue) {

  126.                         String value=(String) itemMap.get(name);

  127.                         try {

  128.                             return Double.parseDouble(value);

  129.                         } catch (Exception e) {

  130.                             logger.error("配置文件key["+name+"]配置错误,返回默认值"+defaultValue,e);

  131.                             return defaultValue;

  132.                         }

  133.                     }

  134.                     

  135.                     public static Map getItems(){

  136.                         return itemMap;

  137.                     }

  138. }

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

            点击(此处)折叠或打开

  1. <?xml version="1.0" encoding="GBK"?>

  2. <system>

  3.                     <category name="test1" description="配置信息二">

  4.                         <item name="test1-1" value="1" description="" />

  5.                     </category>

  6.                     

  7.                     <category name="test2" description="配置信息二">

  8.                         <item name="test2-1" value="0" description="" />

  9.                         <item name="test2-2" value="12.4" description="" />

  10.                         <item name="test2-3" value="啊啊啊" description="" />

  11.                     </category>

  12. </system>

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

到此,相信大家对“怎么用dom4j读取xml配置文件”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

推荐阅读:
  1. Linq如何读取XML
  2. 使用dom4j读取xml文件的四种方式介绍

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

dom4j xml

上一篇:Mysql 5.6库级表级复制的搭建方法

下一篇:oracle中访问索引的方法有哪些

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》