您的位置:首页 > 移动开发 > Android开发

android中解析复杂xml(XStream简单使用)

2014-02-24 13:01 651 查看
解析xml一般有sax,pull,dom,对与复杂的xml,sax或者pull可能会繁琐了一点,dom应该还行,关于之间的优缺点,网上介绍的很多,在此就不啰嗦了,今天写这个不是用dom去解析复杂的xml,而是用XStream去解析,可以很方便的解析出来。XStream官方介绍(http://xstream.codehaus.org/tutorial.html),里面用法介绍很全面,下面只是简单备注下,留日后可以快速浏览。

<?xml version="1.0" encoding="utf-8"?>
<blog>
<author>
<name>Guilherme Silveira</name>
</author>
<entries>
<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>
</entries>
</blog>


创建对应的实体类,Blog,Author和Entry(对应的类在这就不写了,需要说下的是,里面的属性可以没有setter和getter方法,xstram通过反射给里面的属性赋值的),解析上面xml的时候,注意这些实体类必须用空参数构造方法。

InputStream is = getAssets().open("test.xml");
XStream xstream = new XStream();
xstream.alias("blog", Blog.class);	//<blog>标签关联到Blog类(如果<blog>是<包名.Blog>,就可以不用这句)
xstream.alias("entry", Entry.class);
xstream.aliasField("author", Blog.class, "writer");	//如果想将Blog类里面的Author的名字不是author,而是writer,需要加这句话
Blog blog = (Blog) xstream.fromXML(is);


将实体转化成xml,调用 xstream.toXML(Object),更多使用请参考XSream官网。

刚开始尝试写博客,写的不好,欢迎批评

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: