1、下载xstream-1.3.2.jar
2、新建一个web工程,在WebContent里放input.xml文件,其内容如下:
<?xml version="1.0" encoding="UTF-8"?> <root> <models> <model id="0001" name="测试一"> <book id="20091113" name="中国书" /> <book id="20091113" name="中国书" /> <magazine id="2009113" name="中国杂志" time="2009" /> <magazine id="2009113" name="中国杂志" time="2009" /> </model> <model id="0002" name="测试二"> <book id="20091113" name="中国书" /> <book id="20091113" name="中国书" /> <magazine id="2009113" name="中国杂志" time="2009" /> <magazine id="2009113" name="中国杂志" time="2009" /> </model> </models> </root>
3、在src新建2个package——action,dto
4、在action新建5个java bean文件。(拿Root.java做例子,其他不一一列举)
4.1 Root.java
package com.test.xstream_new.model.dto;
import java.util.ArrayList;
import java.util.List;
import com.thoughtworks.xstream.annotations.XStreamAlias;
@XStreamAlias("root")
public class Root {
@XStreamAlias("models")
private List<Model> models = new ArrayList<Model>();
public List<Model> getModels() {
return models;
}
public void setModels(List<Model> models) {
this.models = models;
}
}
4.2 Models.java
4.3 Model.java
4.4 Book.java
4.5 Magazine.java
5、新建一个测试类
package com.test.xstream_new.model.action;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import com.test.xstream_new.model.dto.Root;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
public class main {
/**
* @param args
* @throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
String url = "WebContent/input.xml";
//create(url);
read(url);
}
private static void read(String url) throws FileNotFoundException
{
XStream xs = new XStream(new DomDriver());
xs.processAnnotations(Root.class);//加载别名注释
xs.useAttributeFor(String.class);//定义一个类型转换
InputStream is=null;
Root models = null;
try
{
is=new BufferedInputStream(new FileInputStream(new File(url)));
models = (Root)xs.fromXML( is);
}
finally
{
System.out.println(xs.toXML(models));
try {
is.close();
} catch (IOException e) {
}
}
}
}