XStream别名;元素转属性;去除集合属性(剥皮);忽略不需要元素

时间:2021-08-02 12:46:34

city

package xstream;

public class City {
private String name;
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;
}
public City(String name, String description) {
this.name = name;
this.description = description;
}
}

province

package xstream;

import java.util.ArrayList;
import java.util.List; public class Province {
private String 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;
}
public Province(String name, List<City> cities) {
super();
this.name = name;
this.cities = cities;
} public Province() {} public Province(String name) {
this.name = name;
}
}

 测试类

 

package xstream;

import java.util.ArrayList;
import java.util.List; import org.junit.Test; import com.thoughtworks.xstream.XStream; public class TestXStream {
public List<Province> getProvinceList(){
List<Province> provinceList = new ArrayList<Province>(); Province p1 = new Province("北京");
p1.addCity(new City("东城区","东城区"));
p1.addCity(new City("西城区","西城区")); Province p2 = new Province("上海");
p2.addCity(new City("徐汇区","徐汇区"));
p2.addCity(new City("浦东新区","浦东新区")); provinceList.add(p1);
provinceList.add(p2); return provinceList;
}
//--->原生版
@Test
public void fun(){
List<Province> proList = getProvinceList();
XStream xStream = new XStream();
String xml = xStream.toXML(proList);
System.out.println(xml);
} //--->修改
@Test
public void fun1(){
List<Province> proList = getProvinceList();
XStream xStream = new XStream(); //别名
xStream.alias("china", java.util.List.class);
xStream.alias("province", Province.class);
xStream.alias("city", City.class); //把子元素变成父元素的属性
xStream.useAttributeFor(Province.class, "name"); //去掉容器,"剥皮"
xStream.addImplicitCollection(Province.class, "cities"); //忽略不需要的属性-xml的元素
xStream.omitField(City.class, "description"); String xml = xStream.toXML(proList);
System.out.println(xml);
} }

 

子元素转换成属性

XStream别名;元素转属性;去除集合属性(剥皮);忽略不需要元素


去掉集合元素("剥皮")

XStream别名;元素转属性;去除集合属性(剥皮);忽略不需要元素


忽略不需要的元素

XStream别名;元素转属性;去除集合属性(剥皮);忽略不需要元素