今天閒來無事,突然發現接口傳過來的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();
}
實現方法:在資源文件中有源碼