xml文件流与javabean之间的通用转换(下)

这个比较简单,接上一篇 。 传入javabean,生成xml文档字符串

根据上一篇文章中两位兄弟提示,有空的时候我在看看jax,用这种方式来实现。

 

 

代码如下:

1、主程序

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.dom4j.*;

public class Bean4xml {

	public static String parseBean4Xml(Object model) {
		
		//创建一个document对象
		Document xmlDoc = DocumentHelper.createDocument();
		String rootName = model.getClass().getSimpleName();
		//设置根节点(这里使用类名作为根节点)
		Element root = xmlDoc.addElement(rootName);
		//得到所有声明的方法
		Method[] methods = model.getClass().getDeclaredMethods();
		//得到所有属性
		Field[] fields = model.getClass().getDeclaredFields();
		for (Method method : methods) {
			//过滤出所有get方法
			if (method.getName().indexOf("get") > -1) {
				for (Field field : fields) {
					//匹配字段,并调用get方法,为element设置text值
					if (method.getName().indexOf(
							field.getName().substring(0, 1).toUpperCase()
									.concat(field.getName().substring(1))) > -1) {
						try {
							root.addElement(field.getName()).setText(
									(String) method.invoke(model,
											new Object[] {}));
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
		System.out.println(xmlDoc.asXML());
		return xmlDoc.asXML();
	}

	public static ChargeXmlModel createBean() {
		ChargeXmlModel model = new ChargeXmlModel();
		model.setCsn("20110926");
		model.setMethodName("getMpay");
		model.setMoney("1000.00");
		model.setPassword("123456");
		model.setTerminalid("88884444");
		model.setType("1");
		return model;
	}

	public static void main(String[] args) {
		parseBean4Xml(createBean());
	}
}

 

2、javaBean

 

public class ChargeXmlModel {
	private String methodName;
	private String type;
	private String terminalid;
	private String money;
	private String csn;
	private String password;

	public String getMethodName() {
		return methodName;
	}

	public void setMethodName(String methodName) {
		this.methodName = methodName;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getTerminalid() {
		return terminalid;
	}

	public void setTerminalid(String terminalid) {
		this.terminalid = terminalid;
	}

	public String getMoney() {
		return money;
	}

	public void setMoney(String money) {
		this.money = money;
	}

	public String getCsn() {
		return csn;
	}

	public void setCsn(String csn) {
		this.csn = csn;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
}

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值