xml文件与obj的最简单转换

来源:互联网 发布:剑三萝莉精致捏脸数据 编辑:程序博客网 时间:2024/06/02 19:50

前言:

上篇文章介绍了objToxml文件之后篇幅不够放在这里写了,这个完之后还要介绍一个最简单的方法进行Obj2Xml之间的工具方法。
一、根据上篇文章生成的xml文件来实现tobean的转换:
@Test
public void testToBeanFile() throws Exception{
String url = "D:"+File.separator+"test"+File.separator;
Person person = XMLUtil.toBeanFromFile(url, "test.xml", Person.class);
System.out.println(JSONObject.toJSONString(person));
}
运行之后,返回结果是:
{"fax":{"code":20,"number":"020221327"},"firstName":"sunzy","friend":{"name":["A1","A2","A3"]},"lastName":"youlong","pet":{"animalList":[{},{}]},
"tel":{"code":137280,"number":"137280968"}}
二、超简单转换工具方法:
实现xml向obj的转换
public static <T> T toBean(File file, Class<T> cls) throws IOException
{

if (!file.exists())
return null;
Xstream.processAnnotations(cls);
@SuppressWarnings("unchecked")
T t = (T) Xstream.fromXML(FileUtils.readFileToString(file, "UTF-8"));
return t;
}
测试方法:
@Test
public void testXmlUtilTobean() throws IOException{
String url = "D:"+File.separator+"test"+File.separator+"test.xml";
File file = new File(url);
Person bean = XmlUtil.toBean(file, Person.class);
System.out.println(bean.getFirstName());
}
测试结果:
{"fax":{"code":20,"number":"020221327"},"firstName":"sunzy","friend":{"name":["A1","A2","A3"]},"lastName":"youlong",
"pet":{"animalList":[{},{}]},"tel":{"code":137280,"number":"137280968"}}
obj向xml的简单方法:
public static boolean toXmlFile(File file, Object obj) throws IOException
{
Xstream.processAnnotations(obj.getClass());
String xml = Xstream.toXML(obj);
FileUtils.write(file, xml, "utf-8");
log.info("Xml Create Success:"+file.getAbsolutePath());
return true;
}
测试方法:
 String url = "D:"+File.separator+"test"+File.separator+"test.xml";
File file = new File(url);
try {
boolean a = XMLUtil.toXmlFile(file, per);
System.out.println(a);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
运行结果与流处理结果一致;
FileUtils.write();方法已经对OutputStream进行了封装,所进行的操作与xmlToObj的相互转换所进行的操作完全一致.


原创粉丝点击