我们很多人都处理过XML文件,也有很多非常成熟的第三方开源软件。如:jdom、dom4j等。虽然他们的功能非常强大,但在使用上还是有点不那么习惯。对于格式比较固定的XML文档,它的结构没有变化或是很少变化,这时将它转换成我们熟悉的Java对象来操作的话,会使工作变得更容易一些,而xstream正好可以满足这一点。
本文所用xstream的版本为:1.4.7
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.7</version>
</dependency>
还是以之前的book XML为例,先上代码。
import com.thoughtworks.xstream.annotations.XStreamAlias
import com.thoughtworks.xstream.annotations.XStreamAsAttribute
@XStreamAlias("book")
public class Book {
// 别名注解,这个别名就是XML文档中的元素名,Java的属性名不一定要与别名一致
@XStreamAlias("name")
private String name
@XStreamAlias("author")
private String author
// 属性注解,此price就是book的属性,在XML中显示为:<book price="108">
@XStreamAsAttribute()
@XStreamAlias("price")
private String price
省略get和set方法
}
import java.util.List
import com.thoughtworks.xstream.annotations.XStreamAlias
import com.thoughtworks.xstream.annotations.XStreamImplicit
@XStreamAlias("books")
public class Books {
// 隐式集合,加上这个注解可以去掉book集合最外面的<list></list>这样的标记
@XStreamImplicit
private List<Book>list
省略get和set方法
}