package com.co.lane.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.Element;
/**
* 配置文件内部元素值获取
*/
public class ConfigUtil {
/**
* private Document
*/
private Document doc = null;
/**
* private constructor
*/
public ConfigUtil() {
}
/**
* 取得配置文件中的节点,如下文件跟节点root<br>
* <pre>
* <root>
* <item>
* <Id>H000001</Id>
* <Title>node1</Title>
* <Type>DB</Type>
* <Field>DBVal</Field>
* <Height>10</Height>
* </item>
* <item>
* <Id>H000002</Id>
* <Title>node2</Title>
* <Type>DB</Type>
* <Field>DBVal</Field>
* <Height>100</Height>
* </item>
* </root>
* if xpathExpression is [/call/item], return [{Id=H000001,Title=node1,...}, {Id=H000002,Title=node2,...}]
* </pre>
*
* @param xpathExpression
* @return
* <code>
* List<Map<String,String>> Object instance
* <code>
*/
@SuppressWarnings("unchecked")
public List<Map<String,String>> getListByXPath(String xpathExpression) {
List<Map<String,String>> list = new ArrayList<Map<String,String>>();
List<?> listNodes = doc.selectNodes(xpathExpression);
Iterator<?> iterator = listNodes.iterator();
while(iterator.hasNext()){
Element item = (Element)iterator.next();
List<Element> listSubItem = item.elements();
Map<String,String> map = new HashMap<String, String>();
// 设置对象属性值
for(Element e : listSubItem){
map.put(e.getName(), e.getText());
}
list.add(map);
}
return list;
}
/**
* 取得配置文件中的节点,如下文件跟节点root<br>
* <pre>
* <root>
* <item>
* <Id>H000001</Id>
* <Title>node1</Title>
* <Type>DB</Type>
* <Field>DBVal</Field>
* <Height>10</Height>
* </item>
* <item>
* <Id>H000002</Id>
* <Title>node2</Title>
* <Type>DB</Type>
* <Field>DBVal</Field>
* <Height>100</Height>
* </item>
* </root>
* if xpathExpression is [/call/item], return [{Id=H000001,Title=node1,...}, {Id=H000002,Title=node2,...}]
* </pre>
*
* @param clazzT 泛型对象
* @param xpathExpression
* @return
* <code>
* List<T> Object instance
* <code>
*/
@SuppressWarnings("unchecked")
public <T> List<T> getListByXPath(Class<T> clazzT, String xpathExpression) {
// 反射对象
List<T> list = new ArrayList<T>();
ReflectUtil reflect = ReflectUtil.forClass(clazzT);
// 节点处理
List<?> listNodes = doc.selectNodes(xpathExpression);
Iterator<?> iterator = listNodes.iterator();
String text = "";
while(iterator.hasNext()){
Element item = (Element)iterator.next();
List<Element> listSubItem = item.elements();
try {
// 实例化对象
T instance = clazzT.newInstance();
for(Element e : listSubItem){
// 设置对象属性值
text = StringUtil.escapeCharacter(e.getText());
reflect.setSetMethodValue(instance, e.getName().toLowerCase(), text);
}
list.add(instance);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
return list;
}
// =========================SETTER GETTER==================================
/**
* @return the doc
*/
public Document getDoc() {
return doc;
}
/**
* @param doc
* the doc to set
*/
public void setDoc(Document doc) {
this.doc = doc;
}
}