欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

将javabean转化成xml格式

程序员文章站 2022-03-02 10:28:30
...
package test;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

public class XmlReflector {
	private Class sourceClass;
	private BeanInfo beanInfo;
	private String name;

	XmlReflector(Class sourceClass, String name) throws Exception {
		this.sourceClass = sourceClass;
		this.name = name;
		beanInfo = Introspector.getBeanInfo(sourceClass);
	}

	public String convertToXml(Object o) throws Exception {
		StringBuffer returnValue = new StringBuffer("");
		if (o.getClass().isAssignableFrom(sourceClass)) {
			PropertyDescriptor[] pd = beanInfo.getPropertyDescriptors();
			if (pd.length > 0) {
				returnValue.append("<" + name + ">");
				for (int i = 0; i < pd.length; i++) {
					returnValue.append(getProp(o, pd[i]));
				}
				returnValue.append("</" + name + ">");
			} else {
				returnValue.append("<" + name + "/>");
			}
		} else {
			throw new ClassCastException("Class " + o.getClass().getName()
					+ " is not compatible with " + sourceClass.getName());
		}
		return returnValue.toString();
	}

	private String getProp(Object o, PropertyDescriptor pd) throws Exception {
		StringBuffer propValue = new StringBuffer("");
		Method m = pd.getReadMethod();
		Object ret = m.invoke(o);
		if (null == ret) {
			propValue.append("<" + pd.getName() + "/>");
		} else {
			propValue.append("<" + pd.getName() + ">");
			propValue.append(ret.toString());
			propValue.append("</" + pd.getName() + ">");
		}
		return propValue.toString();
	}
}