import com.thoughtworks.xstream.XStream;
public class PartyList {
// 对象 转 xml 序列化操作
@Test
public void createPartylist() throws IOException, IOException {
// 构建acotr 对象 和 对象 集合
List<Acotr> acotrList = new ArrayList<Acotr>();
Acotr acotr01 = new Acotr("A001", "刘德华", "忘情水", "singer");
Acotr acotr02 = new Acotr("A002", "张学友", "一路上有你", "singer");
Acotr acotr03 = new Acotr("B001", "郭德纲", "我要上春晚", "language");
Acotr acotr04 = new Acotr("B002", "赵本山", "卖拐", "language");
Acotr acotr05 = new Acotr("C001", "小彩旗", "转圈", "dancer");
Acotr acotr06 = new Acotr("C002", "杨丽萍", "雀之恋", "dancer");
Acotr acotr07 = new Acotr("D001", "刘谦", "鸡蛋取戒指", "magic");
Acotr acotr08 = new Acotr("D002", "yif", "空气中抽出面包", "magic");
// 代码重复
acotrList.add(acotr01);
acotrList.add(acotr02);
acotrList.add(acotr03);
acotrList.add(acotr04);
acotrList.add(acotr05);
acotrList.add(acotr06);
acotrList.add(acotr07);
acotrList.add(acotr08);
for (Acotr acotr : acotrList) {
System.out.println(acotr);
}
// 输出 xml
// 创建 xstream 对象
XStream stream = new XStream();
// 添加 别名
stream.alias("acotr", Acotr.class);
stream.alias("partylist", List.class);
// ( 对象对应的xml标签;对象里面 对应的 属性; xml 文档中 属性名称 )
stream.aliasAttribute(Acotr.class, "id", "ID");
// 开启注解
stream.autodetectAnnotations(true);
// 输出 XML文件----这里 输出的是字符 流 --
-- FileOutputStream 是字节流 输出 --然后通过 OutputStreamWriter 桥梁转变为字符流 输出
stream.toXML(acotrList, new OutputStreamWriter(new FileOutputStream(
"partylist.xml"), "utf-8"));
//
}
}
Xstream --》反序列化 xml转变为对象 -- 还需要继续研究 !