将POJO转化成符合XML格式的字符串

环境:MyEclipse6.5 + DOM4J1.6.1

POJO如下:
package util.bean;
public class UserExtendInfo {	
	private String userName;
	
	private String mobilePhone;
	
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getMobilePhone() {
		return mobilePhone;
	}
	public void setMobilePhone(String mobilePhone) {
		this.mobilePhone = mobilePhone;
	}
}

UserExtendInfo user = new UserExtendInfo();
user.setMobilePhone("1234567");
user.setUserName("Ted Mosby");


转化成的XML字符串:
<?xml version="1.0" encoding="UTF-8"?>
<ResponseMessage>
<UserName>Ted Mosby</UserName>
<MobilePhone>1234567</MobilePhone>
</ResponseMessage>
注:不讲究输出格式。

源码:
package cn.com.test;

import java.lang.reflect.Field;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import util.bean.UserExtendInfo;

public class Test {
	public static void main(String[] args) {
		UserExtendInfo user = new UserExtendInfo();
		user.setMobilePhone("1234567");
		user.setUserName("Ted Mosby");
		
		Field[] fieldArray = user.getClass().getDeclaredFields();
		Document document = DocumentHelper.createDocument();
                //新增根节点<ResponseMessage></ResponseMessage>
		Element rootElement = document.addElement("ResponseMessage");
		String name = null;
		String text = null;
		for(Field field : fieldArray) {
			name = field.getName();
                        //将首字母大写
			name = name.substring(0, 1).toUpperCase()+name.substring(1);
			//禁止Java访问权限检查,使能够访问private修饰的属性变量
			field.setAccessible(true);
			try{
				text = field.get(user).toString();
			}catch(IllegalAccessException ilae) {
				System.out.println(ilae.getMessage());
			}
			rootElement.addElement(name).setText(text);
		}
		System.out.println(document.asXML());
	}

}

你可能感兴趣的:(java,bean,xml)