需要加载三个jar包。xstream-1.4.3.jar,xmlpull-1.1.3.1.jar,kxml2-2.3.0.jar。
Step1:创建一个实现了Serializable接口的类
import java.io.Serializable;
public class Person implements Serializable {
private static final long serialVersionUID = 172447632608611914L;
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
System.out.println("Inside Person's Constructor");
this.name = name;
this.age = age;
}
String getName() {
return name;
}
int getAge() {
return age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
Step2:通过xstream.toXML方法写入xml文件
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.thoughtworks.xstream.XStream;
public class WritePersonToXML {
private static List<Person> persons = new ArrayList<Person>();
public static void main(String[] args) throws IOException {
initData();
String path = "xml/myPerson.xml";
FileOutputStream fileOut = null;
XStream out = null;
try {
fileOut = new FileOutputStream(path);
out = new XStream();
out.toXML(persons, fileOut);
System.out.println("序列化XML文件成功");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fileOut != null)
fileOut.close();
}
}
public static void initData() {
for (int i = 1; i <= 3; i++) {
Person person = new Person("学生" + i, 18 + i);
persons.add(person);
}
}
}
Step3:通过xstream.fromXML读入xml文件并反序列化为对象
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import com.thoughtworks.xstream.XStream;
public class ReadPersonFromXml {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
String path = "xml/myPerson.xml";
FileInputStream fileIn = null;
try {
fileIn = new FileInputStream(path);
XStream in = new XStream();
ArrayList<Person> persons = (ArrayList<Person>) in.fromXML(fileIn);
// ArrayList<Person> persons = (ArrayList<Person>) new
// XStream().fromXML("xml/myPerson.xml");
if (persons != null) {
for (Person p : persons) {
System.out.println(p);
}
} else {
System.out.println("反序列化XML文件失败");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fileIn != null)
fileIn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}