采用XSTREAM开源组件做xml的序列化和反序列化

来源:互联网 发布:手机淘宝怎么上二楼 编辑:程序博客网 时间:2024/04/28 23:31


http://acooly.iteye.com/blog/1332549


@XStreamAlias("User")

public class User
{
    @XStreamAlias("Id")
    public String id;
    
    @XStreamAlias("DisplayName")
    public String displayName;
    
    public User()
    {
        super();
    }


    public User(String id, String displayName)
    {
        super();
        this.id = id;
        this.displayName = displayName;
    }

}


@XStreamAlias("Content")
public class Content
{
    @XStreamAlias("Id")
    public String id;
    
    @XStreamAlias("Name")
    public String name;
    
    @XStreamAlias("Value")
    public String value;
    
    public Content(String id, String name, String value)
    {
        super();
        this.id = id;
        this.name = name;
        this.value = value;
    }
    
}


@XStreamAlias("TestXstream")
public class TestXstream
{
    // 标记为节点属性
    @XStreamAsAttribute
    protected String xmlns = "http://s3.amazonaws.com/doc/2006-03-01";
    
    // 忽略该属性
    @XStreamOmitField
    public String ignoreProperty;
    
    // 序列化别名
    @XStreamAlias("Name222")
    public String name;
    
    @XStreamAlias("Type")
    public String type;
    
    public Map<String, String> map = new HashMap<String, String>();
    
    @XStreamAlias("Users")
    public List<User> users = new ArrayList<User>();
    
    public List<Content> contents = new ArrayList<Content>();
    
    public TestXstream()
    {
        super();
    }
    
    public TestXstream(String name, String type)
    {
        super();
        this.name = name;
        this.type = type;
    }


    /**
     * 使用DEMO
     * 
     * @param args
     */
    public static void main(String[] args)
    {
        TestXstream tx = new TestXstream("我带中文,yes", "我也特殊字符哈<f>");
        tx.contents.add(new Content("1", "name1", "value1"));
        tx.contents.add(new Content("2", "name2", "value2"));
        tx.users.add(new User("1", "zhansgdfasdf"));
        tx.users.add(new User("2", "asdfasdfasdf"));
        tx.map.put("1", "234234");
        tx.map.put("2", "234234");
        
        // 对象序列化
        XStream xstream = new XStream(new DomDriver());
        xstream.autodetectAnnotations(true);
        // 不序列化contents属性,但是序列化下面的子对象
        xstream.addImplicitCollection(TestXstream.class, "contents");
        // 格式化输出
        System.out.println(xstream.toXML(tx));
        // 无格式输出
        Writer writer = new StringWriter();
        xstream.marshal(tx, new CompactWriter(writer));
        String seri = writer.toString();
        System.out.println(seri);
        // 反序列化
        Object object = xstream.fromXML(seri, new TestXstream());
        System.out.println(object);
    }
    
}




0 0
原创粉丝点击