XML动态生成相对应的类

前端之家收集整理的这篇文章主要介绍了XML动态生成相对应的类前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import net.sf.cglib.beans.BeanGenerator;
import net.sf.cglib.beans.BeanMap;

public class CglibBean {
	/**
	 * 实体Object
	 */
	public Object object = null;
	/**
	 * 属性map
	 */
	public BeanMap beanMap = null;

	public String nodeName = "";

	public String nodeText = "";

	public CglibBean() {
		super();
	}

	@SuppressWarnings("unchecked")
	public CglibBean(Map propertyMap) {
		this.object = generateBean(propertyMap);
		this.beanMap = BeanMap.create(this.object);
	}

	/**
	 * 给bean属性赋值
	 * 
	 * @param property
	 *            属性名
	 * @param value
	 *            值
	 */
	public void setValue(String property,Object value) {
		beanMap.put(property,value);
	}

	/**
	 * 通过属性名得到属性值
	 * 
	 * @param property
	 *            属性名
	 * @return 值
	 */
	public Object getValue(String property) {
		return beanMap.get(property);
	}

	/**
	 * 得到该实体bean对象
	 * 
	 * @return
	 */
	public Object getObject() {
		return this.object;
	}

	@SuppressWarnings("unchecked")
	private Object generateBean(Map propertyMap) {
		BeanGenerator generator = new BeanGenerator();
		Set keySet = propertyMap.keySet();
		for (Iterator i = keySet.iterator(); i.hasNext();) {
			String key = (String) i.next();
			generator.addProperty(key,(Class) propertyMap.get(key));
		}
		return generator.create();
	}
}

import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;

public class XMLTest {
	private static String text = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><books><book id=\"book\"><title id=\"title\">Harry Potterads</title></book></books>";

	@Test
	public void go() {
		SAXReader reader = new SAXReader();
		Document document;
		try {
			document = reader.read(new ByteArrayInputStream(text
					.getBytes("UTF-8")));
			CglibBean cglibBean = create(document.getRootElement(),getChildren(document.getRootElement()));
			StringBuffer sb = new StringBuffer();
			sb.append(getStartNode(cglibBean));
			sb.append(getNodeChildren(cglibBean));
			sb.append("</").append(cglibBean.nodeName).append(">");
			System.out.println(sb.toString());
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// test(root);
		catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@SuppressWarnings("unchecked")
	public String getNodeChildren(CglibBean cglibBean) {
		Map<String,List<CglibBean>> map = (Map<String,List<CglibBean>>) cglibBean
				.getValue("children");
		Set<?> keySet = map.keySet();
		StringBuffer sb = new StringBuffer();
		for (Iterator<?> i = keySet.iterator(); i.hasNext();) {
			String key = (String) i.next();
			List<CglibBean> cglibBeans = map.get(key);
			for (CglibBean bean : cglibBeans) {
				sb.append(getStartNode(bean));
				if (!"".equals(bean.nodeText)) {
					sb.append(bean.nodeText);
				} else {
					sb.append(getNodeChildren(bean));
				}
				sb.append("</").append(bean.nodeName).append(">");
			}
		}
		return sb.toString();
	}

	public String getStartNode(CglibBean cglibBean) {
		Set<?> keySet = cglibBean.beanMap.keySet();
		StringBuffer startNode = new StringBuffer();
		startNode.append("<").append(cglibBean.nodeName);
		for (Iterator<?> i = keySet.iterator(); i.hasNext();) {
			String key = (String) i.next();
			if (key.indexOf(".attr") != -1) {
				String temp = key.substring(0,key.indexOf(".attr"));
				temp = temp.substring(temp.lastIndexOf(".") + 1,temp.length());
				startNode.append(" ").append(temp).append("=\"")
						.append(cglibBean.getValue(key)).append("\"");
			}
		}
		startNode.append(">");
		return startNode.toString();
	}

	public String getNodeText(CglibBean cglibBean) {
		String text = "";
		Set<?> keySet = cglibBean.beanMap.keySet();
		for (Iterator<?> i = keySet.iterator(); i.hasNext();) {
			String key = (String) i.next();
			if (key.indexOf(".text") != -1) {
				text = (String) cglibBean.getValue(key);
			}
		}
		return text;
	}

	@SuppressWarnings("unchecked")
	public Map<String,List<CglibBean>> getChildren(Element element)
			throws ClassNotFoundException {
		Map<String,List<CglibBean>> children = new HashMap<String,List<CglibBean>>();
		for (Element child : (List<Element>) element.elements()) {
			Map<String,List<CglibBean>> cglibBeanMap = getChildren(child);
			CglibBean cglibBean = create(child,cglibBeanMap);
			List<CglibBean> cglibBeanList = children.get(child.getName());
			if (cglibBeanList == null) {
				cglibBeanList = new ArrayList<CglibBean>();
				cglibBeanList.add(cglibBean);
				children.put(child.getName(),cglibBeanList);
			} else {
				cglibBeanList.add(cglibBean);
				children.put(child.getName(),cglibBeanList);
			}
		}
		return children;
	}

	CglibBean cglibBean;

	@SuppressWarnings("unchecked")
	public CglibBean create(Element element,Map<String,List<CglibBean>> children)
			throws ClassNotFoundException {
		HashMap<String,Class<?>> propertyMap = new HashMap<String,Class<?>>();
		for (Attribute attribute : (List<Attribute>) element.attributes()) {
			propertyMap.put(element.getName() + "." + attribute.getName()
					+ ".attr",Class.forName("java.lang.String"));
		}
		propertyMap.put(element.getName() + ".text",Class.forName("java.lang.String"));
		propertyMap.put("children",Class.forName("java.util.Map"));
		// 生成动态 Bean
		CglibBean bean = new CglibBean(propertyMap);
		bean.nodeName = element.getName();
		bean.nodeText = element.getText();
		for (Attribute attribute : (List<Attribute>) element.attributes()) {
			bean.setValue(element.getName() + "." + attribute.getName()
					+ ".attr",attribute.getText());
		}
		bean.setValue(element.getName() + ".text",element.getText());
		bean.setValue("children",children);
		return bean;
	}

}
目前解析思路是:books是一个类,类有个集合属性children,children类型Map<String,List<CglibBean>>,专门存放各种各样的属性,比如:book属性,以此类推。本来想换个思路实现,由于项目没有用到,就停止了。大概说一下另外种做法,books是一个类,类有个book属性,而不是把所有属性全部放在Map<String,List<CglibBean>>中。 原文链接:https://www.f2er.com/xml/299036.html

猜你在找的XML相关文章