XStream是一个JavaBean和XML互转换的根据类库。不需要映射文件,使用简单,不过很久没更新了。
使用很简单,直接代码:
public class Student {
private String firstName;
private String secondName;
private int age;
}
public class Classz {
private String name;
private String id;
private List<Student> students = new LinkedList<Student>();
}
public static void main(String[] args) {
marshall();
unmarshall();
}
public static void marshall() {
Student s = new Student();
s.setAge(26);
s.setFirstName("liu");
s.setSecondName("wh");
Classz c = new Classz();
c.addStudent(s);
c.setName("class name");
// 不指定别名,XML的元素名为类的全限定类名
XStream xStream = new XStream();
System.out.println(xStream.toXML(c));
xStream.alias("student", Student.class);
xStream.alias("class", Classz.class);
System.out.println(xStream.toXML(c));
}
public static void unmarshall() {
String xml = "<class>" +
" <name>class name</name>" +
" <students class=\"linked-list\">" +
" <student>" +
" <firstName>liu</firstName>" +
" <secondName>wh</secondName>" +
" <age>26</age>" +
" </student>" +
" </students>" +
"</class>";
XStream xStream = new XStream(new DomDriver());
xStream.alias("class", Classz.class);
xStream.alias("student", Student.class);
Classz c = (Classz)xStream.fromXML(xml);
System.out.println(c.getName());
}
使用要注意的是:
如果没有为类指定别名,将使用类的全限定类名作为XML元素的名字。
5131




被折叠的 条评论
为什么被折叠?



