java xml生成javabean_xml生成javabean(zhuan)

package com.dom4j;

import java.io.File;

import java.io.FileWriter;

import java.io.IOException;

import java.lang.reflect.Field;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

import java.util.ArrayList;

import java.util.Iterator;

import java.util.List;

import org.dom4j.Document;

import org.dom4j.DocumentHelper;

import org.dom4j.Element;

import org.dom4j.io.OutputFormat;

import org.dom4j.io.SAXReader;

import org.dom4j.io.XMLWriter;

public class Xml2Object{

public static void main(String[] args){

Xml2Object d=new Xml2Object();

User user=new User();

User user1=new User("姓名1",18,"男");

User user2=new User("姓名2",19,"女");

User user3=new User("石头",20,"女");

List users=new ArrayList();

users.add(user1);

users.add(user2);

users.add(user3);

try {

d.writeXmlDocument(user, users, "GBK", "WebRoot/xml/student.xml");

} catch (Exception e) {

System.out.println("生成xml失败");

e.printStackTrace();

}

/*

Xml2Object d=new Xml2Object();

User user=new User();

List list=d.readXML("WebRoot/xml/student.xml",user);

System.out.println("XML文件读取结果:");

for(int i=0;i

User username=(User)list.get(i);

System.out.println("name"+username.getName());

System.out.println("age"+username.getAge());

System.out.println("sex"+username.getSex());

}*/

}

@SuppressWarnings("hiding")

public void writeXmlDocument(T obj,List entityPropertys,String Encode,String XMLPathAndName) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, IOException{

long lasting=System.currentTimeMillis();

XMLWriter writer=null;

OutputFormat format=OutputFormat.createCompactFormat();

format.setEncoding(Encode);//设置XML文件的编码方式

String filePath=XMLPathAndName;

File file=new File(filePath);

if(file.exists()){

file.delete();

}

Document document=DocumentHelper.createDocument();

String rootname=obj.getClass().getSimpleName();

Element root=document.addElement(rootname+"s");

Field[] properties=obj.getClass().getDeclaredFields();

for(T t:entityPropertys){

Element secondRoot=root.addElement(rootname);

for(int i=0;i

Method meth=t.getClass().getMethod(

"get"

+properties[i].getName().substring(0,1).toUpperCase()

+properties[i].getName().substring(1)

);

secondRoot.addElement(

properties[i].getName()

).setText(meth.invoke(t).toString());

}

}

writer =new XMLWriter(new FileWriter(file),format);

writer.write(document);

writer.close();

long lasting2=System.currentTimeMillis();

System.out.println("写入XML文件结束,用时"+(lasting2-lasting)+"ms");

}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值