pom.xml
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.3.1</version>
</dependency>
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
public class XmlUtil{
public static String toXml(Object obj){
XStream xstream=new XStream();
// XStream xstream=new XStream(new DomDriver()); //直接用jaxp dom來解釋
// XStream xstream=new XStream(new DomDriver("utf-8")); //指定編碼解析器,直接用jaxp dom來解釋
////如果沒有這句,xml中的根元素會是<包.類名>;或者說:註解根本就沒生效,所以的元素名就是類的屬性
xstream.processAnnotations(obj.getClass()); //通過註解方式的,一定要有這句話
return xstream.toXML(obj);
}
public static <T> T toBean(String xmlStr,Class<T> cls){
//注意:不是new Xstream(); 否則報錯:java.lang.NoClassDefFoundError: org/xmlpull/v1/XmlPullParserFactory
XStream xstream=new XStream(new DomDriver());
xstream.processAnnotations(cls);
@SuppressWarnings("unchecked")
T obj=(T)xstream.fromXML(xmlStr);
return obj;
}
public static boolean toXMLFile(Object obj, String absPath, String fileName ){
String strXml = toXml(obj);
String filePath = absPath + fileName;
File file = new File(filePath);
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
return false ;
}
}// end if
OutputStream ous = null ;
try {
ous = new FileOutputStream(file);
ous.write(strXml.getBytes());
ous.flush();
} catch (Exception e1) {
return false;
}finally{
if(ous != null )
try {
ous.close();
} catch (IOException e) {
}
}
return true ;
}
}