dom4j解析xml自动注入实体Bean

 
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;




/*
 *   报文以及请求解析
 *   
 * */
public class Templet {


	static Map<String, String> map = new HashMap<String, String>();


	
	/*   
	 * 	  xml映射实体Bean;
	 *    根据实体Bean属性,注入XML字节文本;
	 *    !仅限获取标签内文本!!!
	 *  @ xml 需要解析的XML字符串
	 *  @ t   需要映射的实体Bean
	 *
	 * */
	


	public static <T> T xmlToBean(String xml,T t)
			throws DocumentException, SecurityException, InstantiationException, IllegalAccessException {
		Document doc = DocumentHelper.parseText(xml); // 将字符串转为XML
		Element root = doc.getRootElement(); // 获取根节点
		Map<String, String> map = getElement(root);
		Field[] fields = t.getClass().getDeclaredFields();
		String[] name = new String[fields.length];
		Field.setAccessible(fields, true);
		for (int i = 0; i < name.length; i++) {
			name[i] = fields[i].getName();
			setFieldValue(t, name[i], map.get(name[i]));
		}
		// 赋值后需要清空map
		map.clear();
		return t;
	};




	/**
	 * 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数.
	 */
	public static void setFieldValue(final Object obj, final String fieldName,final Object value) {
		Field field = getAccessibleField(obj, fieldName);


		if (field == null) {
			throw new IllegalArgumentException("Could not find field ["
					+ fieldName + "] on target [" + obj + "]");
		}


		try {
			field.set(obj, value);
		} catch (IllegalAccessException e) {


		}
	}


	/**
	 * 循环向上转型, 获取对象的DeclaredField, 并强制设置为可访问.
	 * 
	 * 如向上转型到Object仍无法找到, 返回null.
	 */
	public static Field getAccessibleField(final Object obj,
			final String fieldName) {
		for (Class<?> superClass = obj.getClass(); superClass != Object.class;
				superClass = superClass.getSuperclass()) {
			try {
				Field field = superClass.getDeclaredField(fieldName);//没有字段的时候 继续向上寻找
				field.setAccessible(true);
				return field;
			} catch (NoSuchFieldException e) {// NOSONAR
				
				// Field不在当前类定义,继续向上转型
			}
		}
		return null;
	}




	/*
	 * @param   root 当前节点
	 * 递归获取当前节点下的所有内容
	 */


	public static Map<String, String> getElement(Element root) {
		
		Iterator ri = root.elementIterator();// 父节点迭代器
		while (ri.hasNext()) {
			Element foo = (Element) ri.next();// 下一个二级节点
			map.put(foo.getName(), foo.getText());
			getElement(foo);
		}
		return map;
	}




}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值