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();
}
}
}
}
}