构造xml并反序列化为实体

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.thoughtworks.xstream.XStream;

public class TestCreateXml {
    public static void main(String[] args) {
        XStream xs = new XStream();
        Document doc = createXmlDocument(Student.class);
        Student x = (Student) xs.fromXML(doc.asXML());
        System.out.println(x);
    }

    private static Document createXmlDocument(Class cl) {
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement(cl.getName());
        Element eName = root.addElement("name");
        eName.setText("哈利波特");
        Element eAge = root.addElement("age");
        eAge.setText("2");
        Element eSex = root.addElement("sex");
        eSex.setText("female");
        return document;
    }
}
import java.io.Serializable;

public class Student  implements Serializable {
    public String name;
    public int age;
    public String sex;
    @Override
    public String toString(){
        return name+" : "+age+" : "+sex;
    }
}

 

posted on 2012-12-05 17:01  雨渐渐  阅读(197)  评论(0编辑  收藏  举报

导航