代码实例:
1.javaBean类:
package com.hsinfo.web.Demo.XStream; public class City { private String name; public City(String name, String description) { this.name = name; this.description = description; } private String description; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
2.javaBean类:
package com.hsinfo.web.Demo.XStream; import java.util.ArrayList; import java.util.List; public class Province { private String name; public Province(String name) { this.name = name; } private List<City> cities = new ArrayList<City>(); public void addCity(City city) { cities.add(city); } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<City> getCities() { return cities; } public void setCities(List<City> cities) { this.cities = cities; } }
3.Main方法测试:
package com.hsinfo.web.Demo.XStream; import java.util.ArrayList; import java.util.List; import com.thoughtworks.xstream.XStream; public class Test { public static void main(String[] args) { Province p1 = new Province("辽宁省"); p1.addCity(new City("沈阳", "shenyang")); p1.addCity(new City("大连", "dalian")); Province p2 = new Province("吉林省"); p2.addCity(new City("长春", "changchen")); p2.addCity(new City("白城", "baicheng")); List<Province> list = new ArrayList<Province>(); list.add(p1); list.add(p2); XStream xstream = new XStream(); //设置别名 xstream.alias("china", List.class); xstream.alias("province", Province.class); xstream.alias("city", City.class); //子元素变为元素属性,例如我们需要把<province>子元素<name>变成:<province name="">样式 // xstream.useAttributeFor(Province.class, "name"); // 去除集合属性对应元素,因为Pronvice类有一个cities成员,所以生成了<cities>元素,但这个元素对XML文档而言没有什么意义,所以我们希望把它去除! // xstream.addImplicitCollection(Province.class, "cities"); // 让类的成员不生成对应XML元素,我们都是每个类,每个成员都有对应的元素(或属性)存在, // 但有时我们并不希望某些类的成员在对应的XML文档中出现,例如我们不希望City类的description成员出现在XML文档中,可以使用下面方法: xstream.omitField(City.class, "description"); String s = xstream.toXML(list); System.out.println(s); } }
推荐博客对XStream的讲解十分详细:http://www.cnblogs.com/LiZhiW/p/4313493.html