将List生成XML文档(字符串)将XML文档(字符串)解析成List,适用于任何对象
package com.glaway.ids.util;
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 java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class BeanModel2 {
private static final String ATTR_ID = "id";// bean的id属性
private static final int NULL_ID = -1;
// 根据bean自动构建xml的root名字
public static String GetRootName(Class<?> bean) {
String root_name = "_" + bean.getSimpleName().toLowerCase() + "s";
return root_name;
}
// 根据bean自动构建xml的child名字
public static String GetElemName(Class<?> bean) {
String elem_name = "_" + bean.getSimpleName().toLowerCase();
return elem_name;
}
// 根据bean和field构建xml中child的attribute名字
public static String GetAttrName(Class<?> bean, Field field) {
String attr_name = bean.getSimpleName().toLowerCase() + "_"
+ field.getName();
return attr_name;
}
// 根据field与element获取此field对应的value
@SuppressWarnings("finally")
public static <T> String GetAttrValue(Field field, T elem) {
String value = "";
try {
Class<?> type = field.getType();// 获取此field的类型
/*
* 下面依次处理 八种基本类型 Timestamp类型 其他类型(带有id属性的bean类型)
*/
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)).getTime() + "";
} 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 <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();
}
@SuppressWarnings({ "unchecked", "finally" })
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) {
/*
* 从这里开始与ParseList是一样的
*/
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);// 创建属性并赋值
}
}
/*
* 这里就是把Parse的返回字串转化为了保存为文件而已
*/
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);// 创建属性并赋值
}
}
/*
* 这里就是把Parse的返回字串转化为了保存为文件而已
*/
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 void main(String[] args) {
List<DemandIndex> demandIndices = new ArrayList<>();
demandIndices.add(new DemandIndex("1","ang","dB","ANGl"));
demandIndices.add(new DemandIndex("2","fff","qm","ANG2"));
/*List<Persion> persions = new ArrayList<>();
persions.add(new Persion(1,"小王","18"));
persions.add(new Persion(2,"小ming","25"));*/
String xml =ParseList(demandIndices,DemandIndex.class);
System.out.println(xml);
System.out.println("=================================================================================================");
List<DemandIndex> list = ParseXML(xml,DemandIndex.class);
list.stream().forEach(System.out::println);
}
}
根据:https://blog.youkuaiyun.com/weixin_38676276/article/details/86649742修改了哈
结果: