该文参考实现自http://hbiao68.iteye.com/blog/1958413
这两天在实现websevice中服务方返回了xml结构的字符串,寻找了几个xml转bean的方法,结合自己的需要,整理实现个通用方法,做个记录
package com.me import java.io.ByteArrayOutputStream; import java.io.StringReader; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; public class aaaa { /** * 将xml 转换为java bean * @param className * @param xmlStr * @return java bean * @throws ClassNotFoundException */ private static Object xml2bean(String className,String xmlStr) throws ClassNotFoundException{ try { JAXBContext context = JAXBContext.newInstance(Class.forName(className)); Unmarshaller unmarshaller = context.createUnmarshaller(); StringReader rd = new StringReader(xmlStr); Object req = (Object)unmarshaller.unmarshal(rd); return req; } catch (JAXBException e) { e.printStackTrace(); return null; } } /** * 将java bean 转换为xml * @param className * @param bean * @return XmlString * @throws ClassNotFoundException */ private static String bean2xml(String className,Object bean) throws ClassNotFoundException{ try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); JAXBContext context = JAXBContext.newInstance(Class.forName(className)); Marshaller marshaller = context.createMarshaller(); marshaller.marshal(bean,baos); return baos.toString(); } catch (JAXBException e) { e.printStackTrace(); return null; } } //测试方法 public static void main(String args[]) throws java.lang.Exception{ //将xml 转换为java bean String xmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\"?> <nacaoRequest> <userName>user</userName> <passWord></passWord> <caInfo></caInfo> <interfaceInfo> <code>01</code><jgdm></jgdm> <jgmc></jgmc> <zjhm></zjhm> </interfaceInfo></nacaoRequest>"; NacaoRequest req1 = (NacaoRequest)xml2bean(NacaoRequest.class.getName(),xmlStr); System.out.println(req1.getUserName()); //将java bean 转换为xml InterfaceInfo inf = new InterfaceInfo("02","03","04","05");//注意:
//需要转换的NacaoRequest对象一定要添加@XmlRootElement注解,其里面的其他对象则不需要
//需要转换的NacaoRequest对象一定要有不带参数的构造方法,包括该对象里面引用的对象。
<span style="color: rgb(255,0); font-family: Helvetica,Tahoma,Arial,sans-serif; font-size: 14px; line-height: 25.2000007629395px;"></span> NacaoRequest req2 = new NacaoRequest(); req2.setUserName("user"); req2.setPassword("pwd"); req2.setCaInfo("ca"); req2.setInterfaceInfo(inf); String a = bean2xml(NacaoRequest.class.getName(),req2); System.out.println(a); } }希望能起到抛砖引玉的效果。