1. 程式人生 > >Xstream之常用方式與常用註解

Xstream之常用方式與常用註解

  1. import com.thoughtworks.xstream.XStream;  
  2. import com.thoughtworks.xstream.annotations.XStreamAlias;  
  3. import com.thoughtworks.xstream.annotations.XStreamAsAttribute;  
  4. import com.thoughtworks.xstream.annotations.XStreamConverter;  
  5. import com.thoughtworks.xstream.annotations.XStreamImplicit;  
  6. @XStreamAlias("blog")  
  7. public class Blog {  
  8.     @XStreamAsAttribute  
  9.     @XStreamAlias("author")  
  10.     @XStreamConverter(AuthorConverter.class)  
  11.     private Author writer;  
  12.     @XStreamImplicit  
  13.     private List entries = new ArrayList();  
  14.     public Blog(Author writer) {  
  15.         this.writer = writer;  
  16.     }  
  17.     public void add(Entry entry) {  
  18.         entries.add(entry);  
  19.     }  
  20.     public List getContent() {  
  21.         return entries;  
  22.     }  
  23.     public static void main(String[] args) {  
  24.         Blog teamBlog = new Blog(new Author("Guilherme Silveira"));  
  25.         teamBlog.add(new Entry("first", "My first blog entry."));  
  26.         teamBlog  
  27.                 .add(new Entry("tutorial",  
  28.                         "Today we have developed a nice alias tutorial. Tell your friends! NOW!"));  
  29.         XStream xstream = new XStream();  
  30.         xstream.processAnnotations(Blog.class);  
  31.         xstream.processAnnotations(Entry.class);  
  32.         // 重新命名節點名  
  33.         // xstream.aliasPackage("", "xtream");  
  34.         /* 
  35.          * xstream.alias("blog", Blog.class); xstream.alias("entry", 
  36.          * Entry.class); //重新命名屬性名 // xstream.aliasField("author", Blog.class, 
  37.          * "writer"); //去節點 xstream.addImplicitCollection(Blog.class, 
  38.          * "entries"); // xstream.useAttributeFor(Blog.class, "writer"); // 
  39.          * xstream.aliasField("author", Blog.class, "writer"); // 
  40.          * xstream.addImplicitCollection(Blog.class, "entries"); 
  41.          * //使用這個屬性名作為節點上的元素 xstream.useAttributeFor(Blog.class, "writer"); 
  42.          * //重新命名 xstream.aliasField("author", Blog.class, "writer"); //註冊轉換器 
  43.          * xstream.registerConverter(new AuthorConverter()); 
  44.          */  
  45.         System.out.println(xstream.toXML(teamBlog));  
  46.     }  
  47. }