xstream 別名的用法

1.xstream的alias使用方法:

       1.1 作用:將序列化中的類全量名稱,用別名替換。

       1.2  使用方法:xstream.alias("blog", Blog.class);

       1.3  示例:

            要序列化的類:

package test.xstream.test;

public class Author {

    private String name;
    public Author(String name) {
            this.name = name;
    }
    public String getName() {
            return name;
    }
}

        不使用別名alias時序列化出來的xml:

<test.xstream.test.Author>
  <name>name</name>
</test.xstream.test.Author>

使用別名alias時序列化出來的xml:

<Author>
  <name>name</name>
</Author>

2.xstream的aliasField

     2.1 作用:使用別名替代屬性名
     2.2 使用方法:xstream.aliasField("author", Author.class, "name");

    2.3 示例:

不使用別名aliasField時序列化出來的xml:

<Author>
  <name>name</name>
</Author>

使用別名aliasField時序列化出來的xml:

<Author>
  <author>name</author>
</Author>

    3. xstream的useAttributeFor    

3.1 作用:將某一個類的屬性,作爲xml頭信息的屬性,而不是子節點    

3.2 使用方法:xstream.useAttributeFor(Author.class, "name");   

3.3  示例: 不使用別名useAttributeFor時序列化出來的xml:

<Author> <author>name</author> </Author>

使用別名useAttributeFor時序列化出來的xml:

<Author name="name"/>

    ps: 使用方法

    public static void main(String[] args) {
        XStream xstream = new XStream();
        xstream.alias("Author", Author.class);
//        xstream.aliasField("author", Author.class, "name");
        xstream.useAttributeFor(Author.class, "name");
        Author author =new Author("name");
        String xmlString =xstream.toXML(author);
        System.out.println(xmlString);
    }

幾個相關網址:http://xstream.codehaus.org/alias-tutorial.html

http://blog.csdn.net/faye0412/article/details/6602144
發佈了53 篇原創文章 · 獲贊 16 · 訪問量 75萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章