Province class
package com.apptest.xstream.test; import java.util.ArrayList; import java.util.List; public class Province { private String name; private List<City> list = new ArrayList<City>(); public String getName() { return name; } public void setName(String name) { this.name = name; } public List<City> getList() { return list; } public void setList(List<City> list) { this.list = list; } public void addCity(City city) { this.list.add(city); } @Override public String toString() { return "Province [name=" + name + "]"; } }
City class
package com.apptest.xstream.test; public class City { private String name; private String description; public City(String name, String description) { super(); this.name = name; this.description = 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; } @Override public String toString() { return "City [name=" + name + ", description=" + description + "]"; } }
Test class
package com.apptest.xstream.test; import java.util.ArrayList; import java.util.List; import org.junit.Test; import com.thoughtworks.xstream.XStream; public class XStreamDemo { /** * 获取省份list * @return ArrayList<Province> list */ public List<Province> getProvinceList() { Province p1 = new Province(); p1.setName("江西"); p1.addCity(new City("萍乡市","PingXiang")); p1.addCity(new City("上饶市","ShangRao")); Province p2 = new Province(); p2.setName("上海"); p2.addCity(new City("闸北区","ZhaBeiQu")); p2.addCity(new City("徐汇区","XuHuiQu")); List<Province> list = new ArrayList<Province>(); list.add(p1); list.add(p2); return list; } @Test public void func1() { List<Province> list = getProvinceList(); XStream xStream = new XStream(); xStream.alias("china", List.class); xStream.alias("province", Province.class); xStream.alias("city", City.class); xStream.useAttributeFor(Province.class, "name"); xStream.addImplicitCollection(Province.class, "list"); xStream.omitField(City.class, "description"); String s = xStream.toXML(list); System.out.println(s); } }
Result
<china> <province name="江西"> <city> <name>萍乡市</name> </city> <city> <name>上饶市</name> </city> </province> <province name="上海"> <city> <name>闸北区</name> </city> <city> <name>徐汇区</name> </city> </province> </china>
时间: 2024-10-27 06:36:35