导入的包:xstream-1.4.8.jar
package model;
import java.util.ArrayList;
import java.util.List;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
public class XML2OBJ {
public static void main(String[] args) {
Book book = new Book("first", 2);
Book book1 = new Book("second",3);
List<Book> list = new ArrayList<Book>();
list.add(book);
list.add(book1);
XStream xstream = new XStream(new DomDriver());
//标签别名
xstream.alias("list", list.getClass());
xstream.alias("book", Book.class);
String str = xstream.toXML(list);
System.out.println(str);
List<Book> list2 = (List<Book>) xstream.fromXML(str);
for(Book book2 : list2){
System.out.println(book2.getName()+book2.getNum());
}
/*输出情况
* <list>
<book>
<name>first</name>
<num>2</num>
</book>
<book>
<name>second</name>
<num>3</num>
</book>
</list>
first2
second3*/
}
}