使用Xstream,javabean转化为xml

一、最终效果

二、代码内容

1、测试的实体bean(User/Customer)

import java.util.List;
import com.thoughtworks.xstream.annotations.XStreamAlias;
 
//别名注解,作用目标: 类,字段
@XStreamAlias("user")
public class User {
    
    private String name;
    private Integer age;
    
    @XStreamAlias("customerList")
    private List<Customer> customer;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    
    public List<Customer> getCustomer() {
        return customer;
    }
    public void setCustomer(List<Customer> customer) {
        this.customer = customer;
    }
}

import com.thoughtworks.xstream.annotations.XStreamAlias;

@XStreamAlias("customer")
public class Customer {

    private String commodity;

    public String getCommodity() {
        return commodity;
    }

    public void setCommodity(String commodity) {
        this.commodity = commodity;
    }
}

2、测试main

import java.util.ArrayList;
import java.util.List;
import com.thoughtworks.xstream.XStream;

public class XstreamTest {

    public static void main(String[] args) {
        //创建user对象与customer对象并赋值
        User user =  new User();
        Customer customer1 = new Customer();
        Customer customer2 = new Customer();
        customer1.setCommodity("商品1");
        customer2.setCommodity("商品2");
        List<Customer> list = new ArrayList<Customer>();
        list.add(customer1);
        list.add(customer2);
        user.setName("beyondLi");
        user.setAge(23);
        user.setCustomer(list);
        
        String s1 = toXml(user);
        System.out.println(s1);
        
    }


    public static String toXml(Object obj){
        XStream xstream=new XStream();
        xstream.processAnnotations(obj.getClass()); //让类注解生效
        return xstream.toXML(obj);
    }
}

附:所需jar下载路径(http://download.csdn.net/download/u011366045/10219516)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值