javaBean和xml之间的相互转换

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

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

//将xml转为javabean
String xmlStr = "mysql数据库123456" +
"doc_001xiaoxiao_bai1" +
"" +
"00001javaadmin面向对象思想select 1 from SCMS_MaxNo where 1=2" +
"
" +
"
";

//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 list = new ArrayList();
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();
}


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

你可能感兴趣的:(xml/soap/http)