android中解析複雜xml(XStream簡單使用)

解析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官網。

剛開始嘗試寫博客,寫的不好,歡迎批評

大笑



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章