解析XML文件

在项目中,我们经常将配置文件写为xml格式,并在properties文件里,给出xml文件路径。

对于properties文件读取,这里给出propertyUtil工具类。

  在这之前,请注意:Java 的 Properties 加载属性文件后是无法保证输出的顺序与文件中一致的,因为 Properties 是继承自 Hashtable 的, key/value 都是直接存在 Hashtable 中的,而 Hashtable 是不保证进出顺序的。

  解决办法:继承java.util.Properties类,用LinkedHashSet 来保存它的所有 key。

OrderedProperties类如下

package com.test;

import java.util.Collections;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Properties;
import java.util.Set;

public class OrderedProperties extends Properties{

    private static final long serialVersionUID = 1L;
    
    private final LinkedHashSet<Object> keys = new LinkedHashSet<Object>();  
       
    public Enumeration<Object> keys() {  
        return Collections.<Object> enumeration(keys);  
    }  
   
    public Object put(Object key, Object value) {  
        keys.add(key);  
        return super.put(key, value);  
    }  
   
    public Set<Object> keySet() {  
        return keys;  
    }  
   
    public Set<String> stringPropertyNames() {  
        Set<String> set = new LinkedHashSet<String>();  
   
        for (Object key : this.keys) {  
            set.add((String) key);  
        }  
   
        return set;  
    }  

}

读取配置文件properties并解析xml的main方法:

package com.test;


public class T {

    public static void main(String[] args) {
        // 加载properties文件
        propertityUtil pu = propertityUtil.getInstance("project-config.properties");
        // 得到业务配置文件的路径
        String WorkConfigureFile = pu.getProperty("WorkConfigureFile");
        // 解析该xml文件
        ConfigureFileFw configureFileFw = new ConfigureFileFw();
        configureFileFw.parseConfigXmlFile(WorkConfigureFile);
        
        
    }
}

propertityUtil类如下

  1 package com.test;
  2 
  3 import java.io.FileInputStream;
  4 import java.io.FileNotFoundException;
  5 import java.io.FileOutputStream;
  6 import java.io.IOException;
  7 import java.io.OutputStream;
  8 
  9 public class propertityUtil {
 10 
 11     /**
 12      * prop对像
 13      */
 14     private OrderedProperties prop = null;
 15 
 16     /**
 17      * 配置文件位置,默认为***-config.properties
 18      */
 19     private String CONFIGPATH = "project-config.properties";
 20 
 21     /**
 22      * 构造函数
 23      */
 24     public propertityUtil() {
 25         init();
 26     }
 27 
 28     /**
 29      * 构造函数
 30      * 
 31      * @param prop
 32      *            prop对像
 33      */
 34     public propertityUtil(OrderedProperties prop) {
 35         this.prop = prop;
 36     }
 37 
 38     /**
 39      * 构造函数
 40      * 
 41      * @param conf
 42      */
 43     public propertityUtil(String conf) {
 44         this.CONFIGPATH = conf;
 45         init(CONFIGPATH);
 46     }
 47 
 48     /**
 49      * 取得属性
 50      * 
 51      * @return
 52      */
 53     public OrderedProperties getProp() {
 54         return prop;
 55     }
 56 
 57     /**
 58      * 设置属性
 59      * 
 60      * @param prop
 61      */
 62     public void setProp(OrderedProperties prop) {
 63         this.prop = prop;
 64     }
 65 
 66     /**
 67      * 实例
 68      * 
 69      * @param configpath
 70      * @return
 71      */
 72     public static propertityUtil getInstance(String configpath) {
 73         return new propertityUtil(configpath);
 74     }
 75 
 76     /**
 77      * 读取属性文件
 78      * 
 79      * @param configpath
 80      */
 81     private void init(String configpath) {
 82         this.CONFIGPATH = configpath;
 83         init();
 84     }
 85 
 86     /**
 87      * 初始化prop,从文件中读取
 88      */
 89     private void init() {
 90         if (this.CONFIGPATH == null || this.CONFIGPATH.length() == 0) {
 91             System.out.println("No configFile");
 92         } else {
 93 
 94             String srcDir = System.getProperty("user.dir");
 95             srcDir = srcDir + "/resources/properties/" + this.CONFIGPATH;
 96             prop = new OrderedProperties();
 97             FileInputStream fin = null;
 98             try {
 99                 fin = new FileInputStream(srcDir);
100                 prop.load(fin);
101             } catch (FileNotFoundException e2) {
102                 e2.printStackTrace();
103             } catch (IOException e2) {
104                 e2.printStackTrace();
105             }
106 
107             // InputStream is = getClass().getResourceAsStream(this.CONFIGPATH);
108             // prop = new Properties();
109             // try {
110             // prop.load(is);
111             // } catch (Exception e) {
112             // e.printStackTrace();
113             // }
114         }
115     }
116 
117     /**
118      * 取得属性值类
119      * 
120      * @param propName
121      * @return
122      */
123     public String getProperty(String propName) {
124         return getProperty(propName, "");
125     }
126 
127     /**
128      * 取得属性值类
129      * 
130      * @param propName
131      * @return
132      */
133     public String getProperty(String propName, String defValue) {
134         if (prop == null)
135             init();
136         String s = defValue;
137         try {
138             s = prop.getProperty(propName);
139             if (s == null) {
140                 s = defValue;
141             } else {
142                 s = s.trim();
143             }
144         } catch (Exception e) {
145             e.printStackTrace();
146         }
147         return s;
148     }
149 
150     /**
151      * 设置属性
152      * 
153      * @param propName
154      * @param value
155      */
156     public void setProperty(String propName, String value) {
157         if (prop == null)
158             init();
159         try {
160             prop.setProperty(propName, value);
161             storeProperty();
162         } catch (Exception e) {
163             e.printStackTrace();
164         }
165     }
166 
167     /**
168      * 保存属性文件
169      */
170     private void storeProperty() {
171         try {
172             String path = prop.getProperty("path");
173             OutputStream out = new FileOutputStream(path);
174             prop.store(out, " -- sl Soft Config File -- ");
175             out.close();
176         } catch (Exception ioe) {
177             ioe.printStackTrace();
178         }
179     }
180 }
View Code

xml解析类

  1 package com.test;
  2 
  3 import java.io.File;
  4 import java.util.HashMap;
  5 import java.util.List;
  6 import java.util.Map;
  7 import org.dom4j.Document;
  8 import org.dom4j.Element;
  9 import org.dom4j.io.SAXReader;
 10 
 11 /**
 12  * 业务方法配置管理类
 13  * @author 
 14  *
 15  */
 16 public class ConfigureFileFw {
 17     
 18     /**
 19      * 业务方法配置Map
 20      */
 21     private static Map<String, Map<String, String>> workAttributes = new HashMap<String, Map<String, String>>();
 22     
 23     private Document document = null;
 24     
 25     private Element rootElement = null;
 26     
 27     /**
 28      * 获取所有业务
 29      * @return
 30      */
 31     public Map<String, Map<String, String>> getWorkAttributes() {
 32         return workAttributes;
 33     }
 34     /**
 35      * 根据world获取对应业务
 36      * @return
 37      */
 38     public Map<String, String> getWorkAttributesByWorkId(String workId) {
 39         return workAttributes.get(workId);
 40     }
 41     
 42     /**
 43      * 判断是否包含该业务
 44      * @param workId
 45      * @return
 46      */
 47     public String hasWorkId(String workId) {
 48         //Modified by wxq 2016/12/29
 49         //return workAttributes.containsKey(workId);
 50         String temp = "";
 51         for(String configWorkId:workAttributes.keySet()){
 52             if (configWorkId.contains(".*")){
 53                 temp = configWorkId.substring(0,configWorkId.indexOf("."));
 54             }
 55             else{
 56                 temp  = configWorkId;
 57             }
 58             if(workId.contains(temp)){
 59                 return configWorkId;
 60             }
 61         }
 62         return "";
 63         //Ended by wxq 2016/12/29
 64         
 65     }
 66     /**
 67      * 根据业务名称获取业务
 68      * @param workName
 69      * @return
 70      */
 71     public  Map<String, String> getWorkAttributesByWorkName(String workName) {
 72         
 73         for (String str : workAttributes.keySet()) {
 74             Map<String, String> temp = workAttributes.get(str);
 75             if (temp.get("name").equals(workName)) {
 76                 return temp;
 77             }
 78         }
 79         return null;
 80     }
 81     //加入业务方法
 82     private void addToWorkAttributes(String workId, Map<String, String> attrMap) {
 83         workAttributes.put(workId, attrMap);
 84     }
 85     /**
 86      * 根据传入的配置文件,初始化所有业务
 87      * @param fileName
 88      */
 89     public void parseConfigXmlFile(String fileName) {
 90         try {
 91             File f = new File(fileName);
 92             SAXReader reader = new SAXReader();
 93             Document doc = reader.read(f);
 94             rootElement = doc.getRootElement();
 95             if (!rootElement.equals(null)) {
 96                 Element works = (Element)rootElement.element("works");
 97                 List<?> workList = works.elements();
 98                 for (int i = 0; i < workList.size(); i++) {
 99                     Element work = (Element) workList.get(i);
100                     String workID = work.elementText("id");
101                     String workName = work.elementText("name");
102                     String workDescription = work.elementText("description");
103                     String workMethod = work.elementText("method");
104                     String dll = work.elementText("dll");
105                     String class1 = work.elementText("class");
106                     String workSend = work.elementText("send");
107                     String workReceive = work.elementText("receive");
108 
109                     Map<String, String> workAttrMap = new HashMap<String, String>();
110                     workAttrMap.put("id", workID);
111                     workAttrMap.put("name", workName);
112                     workAttrMap.put("description", workDescription);
113                     workAttrMap.put("method", workMethod);
114                     workAttrMap.put("dll", dll);
115                     workAttrMap.put("class", class1);
116                     workAttrMap.put("send", workSend);
117                     workAttrMap.put("receive", workReceive);
118                     workAttributes.put(workID, workAttrMap);
119                 }
120             }
121             
122         } catch (Exception e) {
123             System.out.println("exception:" + e.getMessage());
124         }
125     }
126 
127 }
View Code

 

 

  

posted @ 2017-06-06 16:11  x_jingxin  阅读(302)  评论(0编辑  收藏  举报