Xstream的使用

来源:互联网 发布:mac vim 编辑:程序博客网 时间:2024/06/11 01:33

原文:http://xstream.codehaus.org/alias-tutorial.html

Xstream能很方便的实现XML<->JAVAOBJ,本文记录一下基本操作:

1.根节点
public class Blog {private Author Author;//Author 是BLOG的一级子节点/*entryList是BLOG的一级子节点,entry是entryList的一级子节点,entryList下有多个entry节点*/    private List<Entry> entryList = new ArrayList<Entry>();    public Blog(Author Author) {            this.Author = Author;    }    public void add(Entry entry) {    entryList.add(entry);    }    public List<Entry> getContent() {            return entryList;    }}
2.属性和子节点

public class Entry {private String title, description;    public Entry(String title, String description) {            this.title = title;            this.description = description;    }}

public class Author {// Blog节点的一个属性private String name;// name是Author的子节点    public Author(String name) {            this.name = name;    }    public String getName() {            return name;    }}
添加属性关键类:

public class AuthorConverter implements SingleValueConverter {@Overridepublic boolean canConvert(Class type) {return type.equals(Author.class);}@Overridepublic Object fromString(String arg0) {return new Author(arg0);}@Overridepublic String toString(Object arg0) {return ((Author) arg0).getName();}}

public class XstreamDemo {public static String objToXml() {Blog teamBlog = new Blog(new Author("Guilherme Silveira"));teamBlog.add(new Entry("11", "entry 实体一"));teamBlog.add(new Entry("22", "entry 试题二"));XStream xstream = new XStream();xstream.alias("blog", Blog.class);xstream.alias("entry", Entry.class);// 把标签Author改成writer// xstream.aliasField("writer", Blog.class, "Author");// 删除标签对entryList// xstream.addImplicitCollection(Blog.class, "entryList");// 给blog标签添加一个名为Author的属性xstream.useAttributeFor(Blog.class, "Author");xstream.registerConverter(new AuthorConverter());String xmlStr = xstream.toXML(teamBlog);System.out.println("OBJ——————>>>>>>>>XML \n" + xmlStr + "\n");return xmlStr;}public static void xmlToObj(String xmlStr) {XStream xstream = new XStream();xstream.alias("blog", Blog.class);xstream.alias("entry", Entry.class);Blog blog = (Blog) xstream.fromXML(xmlStr);System.out.println("XML----->OBJ");System.out.println("aa-->" + blog.entryList.size());for (int i = 0; i < blog.entryList.size(); i++) {System.out.println(blog.entryList.get(i));}}}



3.测试:
public class Test {public static void main(String[] args) {String xmlCon = XstreamDemo.objToXml();
XstreamDemo.xmlToObj(xmlCon);}}

4.结果:

OBJ——————>>>>>>>>XML 
<blog Author="Guilherme Silveira">
  <entryList>
    <entry>
      <title>11</title>
      <description>entry 实体一</description>
    </entry>
    <entry>
      <title>22</title>
      <description>entry 试题二</description>
    </entry>
  </entryList>
</blog>


XML----->OBJ
Entry [title=11, description=entry 实体一]
Entry [title=22, description=entry 试题二]

5.相关jar包





原创粉丝点击