使用XStream实现javaBean和xml互转之-----javaBean转xml无格式化
public static XStream getXstream() { return new XStream(new DomDriver("utf-8",new NoNameCoder())){ @Override protected MapperWrapper wrapMapper(MapperWrapper next) { return new MapperWrapper(next) { @Override public boolean shouldSerializeMember(Class definedIn, String fieldName) { if (definedIn == Object.class) { try { return this.realClass(fieldName) != null; } catch (Exception e) { return false; } } else return super.shouldSerializeMember(definedIn, fieldName); } }; } }; } public static String obj2xmlByXStream(Object obj) { XStream xst = getXstream(); xst.processAnnotations(obj.getClass()); /** * 之所以使用下面这种方式生成xml,是因为,默认的toXML()转换后的xml有格式(包含换行符),有格式的xml参与加密会产生许多不必要的问题 * 而下面这种方式转换的xml没有格式 */ StringWriter writer = new StringWriter(); xst.marshal(obj,new CompactWriter(writer)); return writer.toString(); } public static <T> T xml2objByXStream(String xml, Class<T> tClass) { XStream xst = getXstream(); xst.processAnnotations(tClass); return (T) xst.fromXML(xml); }