这个比较简单,接上一篇 。 传入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;
}
}
199

被折叠的 条评论
为什么被折叠?



