最近用到XStream,总结下基本的使用,主要如下:
1.使用类的别名来改变标签的名字
2.使用字段的别名来改变标签的名字
3.使用包的别名来改变标签的名字
4.如果字段类型是由一个SingleValueConverter处理,可写为属性
贴代码:Blog.java
public class Blog {
private Author writer;
private List<Entry> entries = new ArrayList<>();
public Blog(Author writer) {
this.writer = writer;
}
public Author getWriter() {
return writer;
}
public void setWriter(Author writer) {
this.writer = writer;
}
public List<Entry> getEntries() {
return entries;
}
public void setEntries(List<Entry> entries) {
this.entries = entries;
}
public void add(Entry entry) {
entries.add(entry);
}
public List<Entry> getContent() {
return entries;
}
}
public class Author {
private String name;
public Author(String name) {this.name = name;}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
}
Entry.java
public class Entry {
private String title;
private String description;
public Entry(String title, String description) {
this.title = title;
this.description = description;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
XStream.java
public class XStreamTest {
public static void main(String[] args) {
Blog teamBlog =new Blog(new Author("张三"));
teamBlog.add(new Entry("文章1","这是文章1"));
teamBlog.add(new Entry("文章2","这是文章2"));
XStream xstream = new XStream( new DomDriver());
System.out.println(xstream.toXML(teamBlog));
}
}
运行结果:
<myXStream.Blog>
<writer>
<name>张三</name>
</writer>
<entries>
<myXStream.Entry>
<title>文章1</title>
<description>这是文章1</description>
</myXStream.Entry>
<myXStream.Entry>
<title>文章2</title>
<description>这是文章2</description>
</myXStream.Entry>
</entries>
</myXStream.Blog>
修改一下XStream.java
public class XStreamTest {
public static void main(String[] args) {
Blog teamBlog =new Blog(new Author("张三"));
teamBlog.add(new Entry("文章1","这是文章1"));
teamBlog.add(new Entry("文章2","这是文章2"));
XStream xstream = new XStream( new DomDriver());
//用别名“blog”替代Blog.class
xstream.alias("blog", Blog.class);
xstream.alias("Entry", Entry.class);
//用别名“author”替代Blog.class的“write”属性
xstream.aliasField("author", Blog.class, "writer");
//让“entries”不显示
xstream.addImplicitCollection(Blog.class, "entries");
System.out.println(xstream.toXML(teamBlog));
}
}
运行结果:
<blog>
<author>
<name>张三</name>
</author>
<Entry>
<title>文章1</title>
<description>这是文章1</description>
</Entry>
<Entry>
<title>文章2</title>
<description>这是文章2</description>
</Entry>
</blog>