//POJO类:
public class XStreamTestPojo {
public byte id;
public short startLevel;
public short endLevel;
public byte item;
// GETTER & SETTER
public String toString() {
return this.getId() + "==" + this.getStartLevel() + "=="
+ this.getEndLevel() + "==" + this.getItem();
}
}
//Test类:
public class XStreamTestUtil {
public static void main(String[] args) {
XStreamTestPojo pojo = new XStreamTestPojo();
pojo.setId((byte) 1);
pojo.setStartLevel((short) 1);
pojo.setEndLevel((short) 9);
pojo.setItem((byte) 3);
//
XStreamTestPojo pojo1 = new XStreamTestPojo();
pojo1.setId((byte) 2);
pojo1.setStartLevel((short) 10);
pojo1.setEndLevel((short) 19);
pojo1.setItem((byte) 2);
//
List<XStreamTestPojo> pojos = new ArrayList<XStreamTestPojo>();
pojos.add(pojo);
pojos.add(pojo1);
// new XStreamTestUtil().writerXML(pojos);
// new XStreamTestUtil().readXML();
new XStreamTestUtil().addElement(pojo1);
}
public void writerXML(List<XStreamTestPojo> pojo) {
XStream xStream = new XStream(new DomDriver()); // 不需要XPP3库
xStream.alias("TestPOJO", XStreamTestPojo.class);
// xStream.aliasAttribute(XStreamTestPojo.class,"id","编号"); //放为属性
xStream.aliasField("编号", XStreamTestPojo.class, "id"); // 设置别名
try {
FileWriter writer = new FileWriter("pojo.xml");
xStream.toXML(pojo, writer);
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public List<XStreamTestPojo> readXML() {
XStream xStream = new XStream(new DomDriver()); // 不需要XPP3库
xStream.alias("TestPOJO", XStreamTestPojo.class); // 设置类别,或者无法读取报com.thoughtworks.xstream
xStream.aliasField("编号", XStreamTestPojo.class, "id"); // 对类对应,XML文件中的编号对应为iD
Reader reader = null;
try {
reader = new FileReader("pojo.xml");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
List<XStreamTestPojo> pojos = (List<XStreamTestPojo>) xStream
.fromXML(reader);
for (XStreamTestPojo pojo : pojos) {
System.out.println(pojo);
}
return pojos;
}
/**
* API中我没有找到可以直接在尾部添加Element的方法
*
* @param pojo
* 欲添加的Element
* Comment:因为API中无直接添加的方法,所以:先读出元素List,再在List的尾部添加元素,再重新写入XML文件
* 缺点:当文件太大,太多的重复操作,导致资源消耗.
*/
public void addElement(XStreamTestPojo pojo) {
List<XStreamTestPojo> pojos = this.readXML();
pojos.add(pojo);
this.writerXML(pojos);
}
}
XStream入门示例DEMO
最新推荐文章于 2024-08-03 22:24:57 发布