在pom.xml中加入下面的依赖,就可以得到XStream相关的jar了
<dependency>
<groupId>com.thoughtworks.xstream</groupId><artifactId>xstream</artifactId>
<version>1.3.1</version>
</dependency>
package com.mycomp.jaxb;
实体People类(对应people.xml文件读取完后注入到该java类):
import com.thoughtworks.xstream.annotations.XStreamAlias;
@XStreamAlias("people")
public class People {
@XStreamAlias("name")
private String name;
@XStreamAlias("age")
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString(){
return "name: " + this.name + ",age: " + this.age;
}
}
people.xml为与工程的resources文件夹下面:
<people>
<name>小王</name>
<age>21</age>
</people>
读取people.xml文件,并测试打印读取的结果:
package com.mycomp.jaxb; import java.io.InputStream; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.DomDriver; public class TestXstream { public static void main(String[] args) { XStream xStream = new XStream(new DomDriver()); InputStream inputStream = TestXstream.class.getClassLoader().getResourceAsStream("./people.xml"); xStream.processAnnotations(People.class); People people = (People) xStream.fromXML(inputStream); System.out.println(people); } }