import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
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.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import com.longtop.cls.frm.util.StringUtil;
import com.sun.jmx.snmp.Timestamp;
public class XmlUtil {
private static final String ATTR_ID = "id";// bean的id屬性
private static final int NULL_ID = -1;
public static <T> Element parseBean(T t, Class<?> bean,Element el) {
Field[] fields = bean.getDeclaredFields();// 獲得bean的所有屬性
for (Field field : fields) {// 疊代屬性并且指派
int mod = field.getModifiers();
if (Modifier.isFinal(mod) || Modifier.isStatic(mod)
|| Modifier.isPublic(mod)) {
continue;
}
field.setAccessible(true);// 打破封裝性
String attr_name = GetAttrName(bean, field);// 擷取bean屬性對應的xml檔案中的名字
String attr_value = GetAttrValue(field, t);// 擷取此屬性對應的值
// System.out.println(attr_name+"="+attr_value);
el.addElement(attr_name).setText(attr_value);// 建立屬性并指派
}
return el;
}
public static Object xmlStrToBean(Element xmlStr, Class clazz) {
Object obj = null;
try {
// 将xml格式的資料轉換成Map對象
Map<String, Object> map = xmlStrToMap(xmlStr);
//将map對象的資料轉換成Bean對象
obj = mapToBean(map, clazz);
} catch(Exception e) {
e.printStackTrace();
}
return obj;
}
public static <T> String parseList(List<T> list, Class<?> bean) {
Document document = DocumentHelper.createDocument();// 擷取document
document.setXMLEncoding("UTF-8");// 設定編碼
Element root = document.addElement(GetRootName(bean));// 建立根元素
Field[] fields = bean.getDeclaredFields();// 獲得bean的所有屬性
for (T elem : list) {// 開始疊代傳入的list
Element child = root.addElement(GetElemName(bean));// 建立子元素
for (Field field : fields) {// 疊代屬性并且指派
int mod = field.getModifiers();
if (Modifier.isFinal(mod) || Modifier.isStatic(mod)
|| Modifier.isPublic(mod)) {
continue;
}
field.setAccessible(true);// 打破封裝性
String attr_name = GetAttrName(bean, field);// 擷取bean屬性對應的xml檔案中的名字
String attr_value = GetAttrValue(field, elem);// 擷取此屬性對應的值
System.out.println(attr_name+"="+attr_value);
child.addElement(attr_name).setText(attr_value);// 建立屬性并指派
}
}
return document.asXML();
}
// 根據bean自動建構xml的root名字
public static String GetRootName(Class<?> bean) {
//String root_name = "_" + bean.getSimpleName().toLowerCase() + "s";
return null;
}
// 根據bean自動建構xml的child名字
public static String GetElemName(Class<?> bean) {
//String elem_name = "_" + bean.getSimpleName().toLowerCase();
return null;
}
// 根據bean和field建構xml中child的attribute名字
public static String GetAttrName(Class<?> bean, Field field) {
String attr_name =field.getName();
return attr_name;
}
// 根據field與element擷取此field對應的value
@SuppressWarnings("finally")
public static <T> String GetAttrValue(Field field, T elem) {
String value = "";
try {
Class<?> eType = elem.getClass() ;
Class<?> type = field.getType();// 擷取此field的類型
if (type.equals(Byte.class) || type.equals(byte.class)) {
value = field.getByte(elem) + "";
} else if (type.equals(Short.class) || type.equals(short.class)) {
value = field.getShort(elem) + "";
} else if (type.equals(Integer.class) || type.equals(int.class)) {
value = field.getInt(elem) + "";
} else if (type.equals(Long.class) || type.equals(long.class)) {
value = field.getLong(elem) + "";
} else if (type.equals(Float.class) || type.equals(float.class)) {
value = field.getFloat(elem) + "";
} else if (type.equals(Double.class) || type.equals(double.class)) {
value = field.getDouble(elem) + "";
} else if (type.equals(Boolean.class) || type.equals(boolean.class)) {
value = field.getBoolean(elem) + "";
} else if (type.equals(String.class)) {
value = (String) field.get(elem);
} else if (type.equals(Timestamp.class)) {
value = ((Timestamp) field.get(elem)).getDateTime() + "";
} else {
// 如果這個類型有id這個屬性,說明它是個外鍵
Field attr_id = type.getDeclaredField(ATTR_ID);
// 并且此屬性不為null
if (attr_id != null && field.get(elem) != null) {
attr_id.setAccessible(true);
value = attr_id.getInt(field.get(elem)) + "";
}
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} finally {
return value == null ? "" : value;
}
}
public static <T> void SetAttrValue(Field field, T elem, String value) {
try {
Class<?> type = field.getType();
if (type.equals(Byte.class) || type.equals(byte.class)) {
try {
field.setByte(elem, Byte.parseByte(value));
} catch (NumberFormatException e) {
// 數字格式化異常,未做任何處理
}
} else if (type.equals(Short.class) || type.equals(short.class)) {
try {
field.setShort(elem, Short.parseShort(value));
} catch (NumberFormatException e) {
// 數字格式化異常,未做任何處理
}
} else if (type.equals(Integer.class) || type.equals(int.class)) {
try {
field.setInt(elem, Integer.parseInt(value));
} catch (NumberFormatException e) {
field.setInt(elem, NULL_ID);
}
} else if (type.equals(Long.class) || type.equals(long.class)) {
try {
field.setLong(elem, Long.parseLong(value));
} catch (NumberFormatException e) {
// 數字格式化異常,未做任何處理
}
} else if (type.equals(Float.class) || type.equals(float.class)) {
try {
field.setFloat(elem, Float.parseFloat(value));
} catch (NumberFormatException e) {
// 數字格式化異常,未做任何處理
}
} else if (type.equals(Double.class) || type.equals(double.class)) {
try {
field.setDouble(elem, Double.parseDouble(value));
} catch (NumberFormatException e) {
// 數字格式化異常,未做任何處理
}
} else if (type.equals(Boolean.class) || type.equals(boolean.class)) {
try {
field.setBoolean(elem, Boolean.parseBoolean(value));
} catch (Exception e) {
e.printStackTrace();
}
} else if (type.equals(String.class)) {
field.set(elem, value);
} else if (type.equals(Timestamp.class)) {
try {
field.set(elem, new Timestamp(Long.parseLong(value)));
} catch (NumberFormatException e) {
// 如果格式化異常,說明這個Timestamp是個null字串,當麼它的值也為null
field.set(elem, null);
}
} else {
Field attr_id = type.getDeclaredField(ATTR_ID);
if (attr_id != null) {
attr_id.setAccessible(true);
Object external = type.newInstance();
try {
attr_id.setInt(external, Integer.parseInt(value));
field.set(elem, external);
} catch (NumberFormatException e) {
// 如果格式化出現異常,那麼這個外鍵為null
field.set(elem, null);
}
}
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
public static Map<String, Object> xmlStrToMap(Element xmlStr) throws Exception {
if(StringUtil.isEmpty(xmlStr)) {
return null;
}
Map<String, Object> map = new HashMap<String, Object>();
//擷取ReqParam資料
List children = xmlStr.elements();
//循環所有子元素
if(children != null && children.size() > 0) {
for(int i = 0; i < children.size(); i++) {
Element child = (Element)children.get(i);
map.put(child.getName(), child.getTextTrim());
}
}
return map;
}
public static Object mapToBean(Map<String, Object> map, Class clazz) throws Exception {
Object obj = clazz.newInstance();
if(map != null && map.size() > 0) {
for(Map.Entry<String, Object> entry : map.entrySet()) {
String propertyName = entry.getKey();
Object value = entry.getValue();
String setMethodName = "set"
+ propertyName.substring(0, 1).toUpperCase()
+ propertyName.substring(1);
Field field = getClassField(clazz, propertyName);
if(field!=null){
Class fieldTypeClass = field.getType();
value = convertValType(value, fieldTypeClass);
clazz.getMethod(setMethodName, field.getType()).invoke(obj, value);
}
}
}
return obj;
}
private static Object convertValType(Object value, Class fieldTypeClass) {
Object retVal = null;
if(Long.class.getName().equals(fieldTypeClass.getName())
|| long.class.getName().equals(fieldTypeClass.getName())) {
retVal = Long.parseLong(value.toString());
} else if(Integer.class.getName().equals(fieldTypeClass.getName())
|| int.class.getName().equals(fieldTypeClass.getName())) {
retVal = Integer.parseInt(value.toString());
} else if(Float.class.getName().equals(fieldTypeClass.getName())
|| float.class.getName().equals(fieldTypeClass.getName())) {
retVal = Float.parseFloat(value.toString());
} else if(Double.class.getName().equals(fieldTypeClass.getName())
|| double.class.getName().equals(fieldTypeClass.getName())) {
retVal = Double.parseDouble(value.toString());
} else {
retVal = value;
}
return retVal;
}
private static Field getClassField(Class clazz, String fieldName) {
if( Object.class.getName().equals(clazz.getName())) {
return null;
}
Field []declaredFields = clazz.getDeclaredFields();
for (Field field : declaredFields) {
if (field.getName().equals(fieldName)) {
return field;
}
}
Class superClass = clazz.getSuperclass();
if(superClass != null) {// 簡單的遞歸一下
return getClassField(superClass, fieldName);
}
return null;
}
public static <T> List<T> ParseXML(String content, Class<?> bean) {
List<T> elements = new ArrayList<T>();// 建構一個空的list
try {
Document document = DocumentHelper.parseText(content);// 根據傳入的content擷取document
Element rootElement = document.getRootElement();// 擷取根元素
Field[] fields = bean.getDeclaredFields();// 擷取此bean的所有屬性
// 疊代根元素下所有的子元素
for (Iterator<Element> childs = rootElement.elements().iterator(); childs
.hasNext();) {
T element = (T) bean.newInstance();// 根據bean建立一個對象
Element child = childs.next();// 依次擷取子元素
for (Field field : fields) {
int mod = field.getModifiers();
if (Modifier.isFinal(mod) || Modifier.isStatic(mod)
|| Modifier.isPublic(mod)) {
continue;
}
field.setAccessible(true);
String attr_name = GetAttrName(bean, field);// 擷取屬性名
Element param = child.element(attr_name);
// 根據屬性名擷取屬性
String attr_value = param.getText();// 擷取屬性值
SetAttrValue(field, element, attr_value);// 設定屬性值
// System.out.println("->"+attr_name+"="+attr_value);
}
// 判斷該element是否==null?
Field field_id = bean.getDeclaredField(ATTR_ID);
if (field_id != null) {
field_id.setAccessible(true);
if (field_id.getInt(element) == NULL_ID) {
elements.add(null);
continue;
}
}
elements.add(element);// 把初始化好的element添加到elements中
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} finally {
return elements;
}
}
@SuppressWarnings("finally")
public static <T> List<T> ReadListByFile(String path, Class<?> bean) {
List<T> elements = new ArrayList<T>();// 建構一個空的list
try {
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(new File(path));
Element rootElement = document.getRootElement();// 擷取根元素
Field[] fields = bean.getDeclaredFields();// 擷取此bean的所有屬性
// 疊代根元素下所有的子元素
for (Iterator<Element> childs = rootElement.elements().iterator(); childs
.hasNext();) {
T element = (T) bean.newInstance();// 根據bean建立一個對象
Element child = childs.next();// 依次擷取子元素
for (Field field : fields) {
int mod = field.getModifiers();
if (Modifier.isFinal(mod) || Modifier.isStatic(mod)
|| Modifier.isPublic(mod)) {
continue;
}
field.setAccessible(true);
String attr_name = GetAttrName(bean, field);// 擷取屬性名
Element param = child.element(attr_name);
;// 根據屬性名擷取屬性
String attr_value = param.getText();// 擷取屬性值
SetAttrValue(field, element, attr_value);// 設定屬性值
// System.out.println("->"+attr_name+"="+attr_value);
}
// 判斷該element是否==null?
Field field_id = bean.getDeclaredField(ATTR_ID);
if (field_id != null) {
field_id.setAccessible(true);
if (field_id.getInt(element) == NULL_ID) {
elements.add(null);
continue;
}
}
elements.add(element);// 把初始化好的element添加到elements中
}
} catch (Exception e) {
e.printStackTrace();
} finally {
return elements;
}
}
public static <T> void WriteFileByList(String path, List<T> list,
Class<?> bean) {
Document document = DocumentHelper.createDocument();// 擷取document
document.setXMLEncoding("UTF-8");// 設定編碼
Element root = document.addElement(GetRootName(bean));// 建立根元素
Field[] fields = bean.getDeclaredFields();// 獲得bean的所有屬性
for (T elem : list) {// 開始疊代傳入的list
Element child = root.addElement(GetElemName(bean));// 建立子元素
for (Field field : fields) {// 疊代屬性并且指派
int mod = field.getModifiers();
if (Modifier.isFinal(mod) || Modifier.isStatic(mod)
|| Modifier.isPublic(mod)) {
continue;
}
field.setAccessible(true);// 打破封裝性
String attr_name = GetAttrName(bean, field);// 擷取bean屬性對應的xml檔案中的名字
String attr_value = GetAttrValue(field, elem);// 擷取此屬性對應的值
// System.out.println(attr_name+"="+attr_value);
child.addElement(attr_name).setText(attr_value);// 建立屬性并指派
}
}
FileOutputStream fos = null;
XMLWriter writer = null;
try {
fos = new FileOutputStream(path);
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
writer = new XMLWriter(fos, format);
writer.write(document);
writer.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static <T> void AddElementsByList(String path, List<T> list,
Class<?> bean) {
SAXReader saxReader = new SAXReader();
Document document = null;
try {
document = saxReader.read(new File(path));
} catch (Exception e) {
e.printStackTrace();
return;
}
Element root = document.getRootElement();
Field[] fields = bean.getDeclaredFields();// 獲得bean的所有屬性
for (T elem : list) {// 開始疊代傳入的list
Element child = root.addElement(GetElemName(bean));// 建立子元素
for (Field field : fields) {// 疊代屬性并且指派
int mod = field.getModifiers();
if (Modifier.isFinal(mod) || Modifier.isStatic(mod)
|| Modifier.isPublic(mod)) {
continue;
}
field.setAccessible(true);// 打破封裝性
String attr_name = GetAttrName(bean, field);// 擷取bean屬性對應的xml檔案中的名字
String attr_value = GetAttrValue(field, elem);// 擷取此屬性對應的值
// System.out.println(attr_name+"="+attr_value);
child.addElement(attr_name).setText(attr_value);// 建立屬性并指派
}
}
FileOutputStream fos = null;
XMLWriter writer = null;
try {
fos = new FileOutputStream(path);
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
writer = new XMLWriter(fos, format);
writer.write(document);
writer.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}