xstream 实现simplebean2xml ,xml2simplebean
xstream 实现simplebean2xml ,xml2simplebean
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.StaxDriver;
public class WSUtils {
/**
* xml转bean
* @param alias
* @param clazz
* @param xml
* @param <T>
* @return
*/
public static <T> T toBean(String alias,Class<T> clazz, String xml) {
try {
XStream xstream = new XStream(new StaxDriver());
xstream.alias(alias, clazz);
return (T) xstream.fromXML(xml);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("[XStream]XML转对象出错");
}
}
/**
* bean转xml
* @param alias
* @param clazz
* @param obj
* @param <T>
* @return
*/
public static <T> String toxml(String alias,Class<T> clazz, Object obj) {
try {
XStream xstream = new XStream(new StaxDriver());
xstream.alias(alias, clazz);
return xstream.toXML((T)obj);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("[XStream]对象转XML出错");
}
}
复杂的参考官方文档
http://x-stream.github.io/tutorial.html