XML转Bean有很多方式,我使用的是xtream方式实现xml与bean的互转。
下面是简单的xml转bean
/** * XML转换成bean * @param obj * @return yuyuchen */ public static Object XmlTojavaBean(String xmlOut) { Object object = null; try { Class<?> cl = Class.forName(xmlOut); XStream xStreamOut = new XStream(new DomDriver()); xStreamOut.processAnnotations(cl); object = xStreamOut.fromXML(xmlOut); } catch (ClassNotFoundException e) { e.printStackTrace(); } return object; }
下面是需要特殊化处理一些别名,去掉class等
/** * XML转换成bean * @param obj * @return yuyuchen * @throws DocumentException */ public static IEsbServBodyResponse XmlTojavaBeanResp(Class<?> bean,String xmlIn) throws ClassNotFoundException, DocumentException { XStream xStreamIn = new XStream(new DomDriver()); Class<?> clx = bean; // 处理注解 xStreamIn.processAnnotations(clx); // 标签“name”, 解析为clx类 xStreamIn.alias(clx.getSimpleName().toLowerCase(), clx); // 设置标签class属性,为null(组装xml需要用到) xStreamIn.aliasSystemAttribute(null, "class"); xStreamIn.addDefaultImplementation(bean, IEsbServBodyResponse.class);//此处可以转为泛型以适配所有类 // 忽略未知的元素 xStreamIn.ignoreUnknownElements(); Document document = DocumentHelper.parseText(xmlIn); xmlIn = document.getRootElement().asXML(); return (IEsbServBodyResponse) xStreamIn.fromXML(xmlIn); }
bean转xml:
/** * bean转换成XML * @param obj * @return yuyuchen */ public static String javaBeanToXml(Object obj) { XStream xstream = new XStream(new XppDriver(new XmlFriendlyNameCoder("_-", "_")));//别名中如有横杠‘-’或下划线‘_’,xstram会自动转2个下划线,该方法是转为一个下划线 xstream.aliasSystemAttribute(null, "class"); xstream.autodetectAnnotations(true);//开启自动注解 String xmlstr = xstream.toXML(obj); return xmlstr; }