利用dom4j读取XML配置文件

来源:互联网 发布:凤凰卫视直播软件apk 编辑:程序博客网 时间:2024/04/30 01:51

来自http://martin3000.iteye.com/blog/1326578


XMLReader类

Java代码  收藏代码
  1. import java.io.File;  
  2. import java.util.Iterator;  
  3. import org.dom4j.Document;  
  4. import org.dom4j.Element;  
  5. import org.dom4j.io.SAXReader;  
  6.   
  7. /** 
  8.  *  
  9.  * @author Martin3000 
  10.  *  
  11.  */  
  12. public class XMLReader {  
  13.     // 配置文件名  
  14.     private static String filename = "conf.xml";  
  15.     private static Config config;  
  16.   
  17.     /** 
  18.      * 从配置文件中读取参数并保存到Config类中, 
  19.      * 很多时候程序中会多次使用到配置中的参数,  
  20.      * 于是设置成静态方法,读取一次后就一直保存其中的参数, 
  21.      * 不再反复读取 
  22.      *  
  23.      * @return 
  24.      */  
  25.     public static Config loadconfig() {  
  26.         if (config == null)  
  27.             config = getconfig();  
  28.         return config;  
  29.     }  
  30.   
  31.     private static Config getconfig() {  
  32.         Config config = new Config();  
  33.         try {  
  34.             File f = new File(filename);  
  35.             if (!f.exists()) {  
  36.                 System.out.println("  Error : Config file doesn't exist!");  
  37.                 System.exit(1);  
  38.             }  
  39.             SAXReader reader = new SAXReader();  
  40.             Document doc;  
  41.             doc = reader.read(f);  
  42.             Element root = doc.getRootElement();  
  43.             Element data;  
  44.             Iterator<?> itr = root.elementIterator("VALUE");  
  45.             data = (Element) itr.next();  
  46.   
  47.             config.server = data.elementText("server").trim();  
  48.             config.user = data.elementText("user").trim();  
  49.             config.pass = data.elementText("pass").trim();  
  50.             config.port = data.elementText("port").trim();  
  51.             config.dbname = data.elementText("dbname").trim();  
  52.   
  53.         } catch (Exception ex) {  
  54.             System.out.println("Error : " + ex.toString());  
  55.         }  
  56.         return config;  
  57.   
  58.     }  
  59. }  

 

XML文格式(conf.xml)

 

 

Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <CONFIG>  
  3.     <VALUE>  
  4.         <!-- mysql连接设置 -->  
  5.         <server>127.0.0.1</server>  
  6.         <dbname>users</dbname>  
  7.         <user>root</user>  
  8.         <pass>pass</pass>  
  9.         <port>3306</port>  
  10.     </VALUE>  
  11. </CONFIG>   

 


0 0
原创粉丝点击