Xstream之常用方式與常用註解
阿新 • • 發佈:2018-12-14
- import com.thoughtworks.xstream.XStream;
- import com.thoughtworks.xstream.annotations.XStreamAlias;
- import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
- import com.thoughtworks.xstream.annotations.XStreamConverter;
- import com.thoughtworks.xstream.annotations.XStreamImplicit;
- @XStreamAlias("blog")
- public class Blog {
- @XStreamAsAttribute
- @XStreamAlias("author")
- @XStreamConverter(AuthorConverter.class)
- private Author writer;
- @XStreamImplicit
- 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;
- }
- public static void main(String[] args) {
- 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.aliasPackage("", "xtream");
- /*
- * xstream.alias("blog", Blog.class); xstream.alias("entry",
- * Entry.class); //重新命名屬性名 // xstream.aliasField("author", Blog.class,
- * "writer"); //去節點 xstream.addImplicitCollection(Blog.class,
- * "entries"); // xstream.useAttributeFor(Blog.class, "writer"); //
- * xstream.aliasField("author", Blog.class, "writer"); //
- * xstream.addImplicitCollection(Blog.class, "entries");
- * //使用這個屬性名作為節點上的元素 xstream.useAttributeFor(Blog.class, "writer");
- * //重新命名 xstream.aliasField("author", Blog.class, "writer"); //註冊轉換器
- * xstream.registerConverter(new AuthorConverter());
- */
- System.out.println(xstream.toXML(teamBlog));
- }
- }