javaBean和xml之间的相互转换

来源:互联网 发布:nginx 日志记录真实ip 编辑:程序博客网 时间:2024/05/17 00:14

今天闲来无事,突然发现接口传过来的xml一下子就转为了javaBean了,觉得好神奇!就仔细研究了:

先xml转javaBean:根据协议我们接受的数据是xml字符串如下解析

//将xml转为javabean
String xmlStr = "<DocumentVo><title>mysql数据库</title><id>123456</id>" +
"<sourceId>doc_001</sourceId><sourceName>xiaoxiao_bai1</sourceName>" +
"<contentList>" +
"<id>00001</id><name>java</name><createUser>admin</createUser><content>面向对象思想select 1 from SCMS_MaxNo where 1=2</content>" +
"</contentList>" +
"</DocumentVo>";

//DocumentVo 是个javaBean

DocumentVo document = xmlUtils.fromXml(xmlStr);
System.out.println(document.getTitle()+"-----------");

//实现下面方面可能需要的包:commons-beanutils-1.6.jar  commons-betwixt-0.8.jar  commons-digester-1.7.jar commons-collections-3.1.jar  velocity-1.5.jar  commons-lang-2.4.jar  commons-io-1.4.jar

public static DocumentVo fromXml(String xml) throws IOException {
return (DocumentVo) xmlUtils.xml2obj(DocumentVo.class, xml);
}

private static DocumentVo xml2obj(Class<?> c, String xml) {
StringReader xmlReader = new StringReader(xml);
BeanReader br = new BeanReader();
br.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);
br.getBindingConfiguration().setMapIDs(false);
try {
br.registerBeanClass(c.getSimpleName(), c);
return (DocumentVo) br.parse(xmlReader);
} catch (IntrospectionException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
return null;
}


javaBean转为xml,采用velocity模版的方式:

DocumentVo doc = new DocumentVo();
doc.setId("123456");
doc.setSourceName("xiaoxiao_bai1");
doc.setTitle("mysql数据库");
doc.setSourceId("doc_001");
ContentVo content = new ContentVo();
content.setId("00001");
content.setName("java");
content.setCreateUser("admin");
content.setContent("面向对象思想select 1 from SCMS_MaxNo where 1=2");
List<ContentVo> list = new ArrayList<ContentVo>();
list.add(content);
doc.setContentList(list);


String xml = "";
try {
xml = VelocityUtil.getInstance().getRequestXml("doc.vm", "doc", doc);
System.out.println(xml);
} catch (Exception e) {
xml = "";
e.printStackTrace();
}


实现方法:在资源文件中有源码