xml转换成bean

实现类
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.lang.reflect.Method;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class ReadXMLUtil<T> {
	public T toEntity(Class<T> clazz, String xmlStr) throws Exception {
		// System.out.println(xmlStr);
		T t = null;
		Document doc = null;
		DocumentBuilder builder = null;
		// parse the xmlStr to DOM document
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		builder = factory.newDocumentBuilder();
		InputStream is = null;
		if (xmlStr.indexOf("encoding=\"GBK\"") >= 0) {
			is = new ByteArrayInputStream(xmlStr.getBytes("GBK"));
		} else {
			is = new ByteArrayInputStream(xmlStr.getBytes("utf-8"));
		}
		doc = builder.parse(is);
		if (doc == null)
			return null;
		t = clazz.newInstance();
		Method[] methods = clazz.getMethods();
		// read value from document by reflection
		for (Method method : methods) {
			if (!method.getName().substring(0, 3).equals("set")) {
				continue;
			}
			String methodName = method.getName();
			String propertyName;
			if ("setLoginNum".equals(methodName)) {
				propertyName = methodName.substring(3, 4)
						+ methodName.substring(4, method.getName().length());
			}else {
				propertyName = methodName.substring(3, 4).toLowerCase()
						+ methodName.substring(4, method.getName().length());
			}
			try {
				NodeList nl = doc.getElementsByTagName(propertyName);
				if (nl.getLength() < 1)
					continue;
				Node n = nl.item(0);
				if (n == null)
					continue;
				String value = n.getTextContent();
				method.invoke(t, value);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				throw e;
			}
		}

		return t;
	}
调用方法:
ReadXMLUtil<UserAuth> readXML = new ReadXMLUtil<UserAuth>();
userAuth = readXML.toEntity(UserAuth.class, respXML);

猜你喜欢

转载自huweiyi.iteye.com/blog/2360870