1、在模块目录下创建action,dto两个package。
2、在action中创建AuthorConverter.java和xstream_main.java文件
2.1——AuthorConverter.java
package com.test.xstream.blog.action; import com.test.xstream.blog.dto.Author; import com.thoughtworks.xstream.converters.SingleValueConverter; public class AuthorConverter implements SingleValueConverter { public String toString(Object obj) { return ((Author) obj).getName(); } public Object fromString(String name) { return new Author(name); } public boolean canConvert(Class type) { return type.equals(Author.class); } }
2.2——xstream_main.java
package com.test.xstream.blog.action; import java.io.FileNotFoundException; import com.test.xstream.blog.dto.Author; import com.test.xstream.blog.dto.Blog; import com.test.xstream.blog.dto.Entry; import com.thoughtworks.xstream.XStream; public class xstream_main { public static void main(String[] args) throws FileNotFoundException { Blog teamBlog = new Blog(new Author("Guilherme Silveira")); teamBlog.add(new Entry("first","My first blog entry.")); teamBlog.add(new Entry("tutorial","Today we have developed a nice alias tutorial. Tell your friends! NOW!")); XStream xstream = new XStream(); //取别名 xstream.processAnnotations(Blog.class); xstream.processAnnotations(Entry.class); xstream.addImplicitCollection(Blog.class, "entries");//去掉entries标签 xstream.useAttributeFor(Blog.class, "writer"); xstream.registerConverter(new AuthorConverter()); // FileOutputStream file = new FileOutputStream("WebContent/xml/blog.xml"); // // xstream.toXML(teamBlog, file); System.out.println(xstream.toXML(teamBlog)); } }
3、在dto中创建Author.java、Blog.java、Entry.java文件。分别对应于xml文件中的<blog author="">、<blog>、<entry>。
3.1——Author.java
package com.test.xstream.blog.dto; public class Author { private String name; public Author(String name) { this.name = name; } public String getName() { return name; } }
3.2——Blog.java
package com.test.xstream.blog.dto; import java.util.ArrayList; import java.util.List; import com.thoughtworks.xstream.annotations.XStreamAlias; @XStreamAlias("blog") public class Blog { @XStreamAlias("author") private Author writer; private List entries = new ArrayList(); public Blog(Author writer) { this.writer = writer; } public void add(Entry entry) { entries.add(entry); } public List getContent() { return entries; } }
3.3——Entry.java
package com.test.xstream.blog.dto; import com.thoughtworks.xstream.annotations.XStreamAlias; @XStreamAlias("entry") public class Entry { private String title, description; public Entry(String title, String description) { this.title = title; this.description = description; } }
4、blog.xml文件内容如下:
<?xml version="1.0" encoding="UTF-8"?> <blog author="Guilherme Silveira"> <entry> <title>first</title> <description>My first blog entry.</description> </entry> <entry> <title>tutorial</title> <description>Today we have developed a nice alias tutorial. Tell your friends! NOW!</description> </entry> </blog>