android XMl 解析神奇xstream 四: 將複雜的xml檔案解析為對象,androidxstream

來源:互聯網
上載者:User

android XMl 解析神奇xstream 四: 將複雜的xml檔案解析為對象,androidxstream

前言:對xstream不理解的請看:

android XMl 解析神奇xstream 一: 解析android項目中 asset 檔案夾 下的 aa.xml 檔案

android XMl 解析神奇xstream 二: 把對象轉換成xml

android XMl 解析神奇xstream 三: 把複雜物件轉換成 xml

 

1、檔案準備

把一個預先寫好的xml檔案放在android項目目錄的 asset 檔案夾。

檔案內容為:

<blog>  <age>30</age>  <name>jhon</name>  <person>    <pAge>36</pAge>    <pName>saliy</pName>  </person></blog>

 

 

2、javaBeen

package com.android10;public class Person {    String pName ;    String pAge  ;        public String getpName() {        return pName;    }    public void setpName(String pName) {        this.pName = pName;    }    public String getpAge() {        return pAge;    }    public void setpAge(String pAge) {        this.pAge = pAge;    } }

 

package com.android10;public class Product {    private String name ;    private String age  ;    private Person person ;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getAge() {        return age;    }    public void setAge(String age) {        this.age = age;    }    public Person getPerson() {        return person;    }    public void setPerson(Person person) {        this.person = person;    }}


3、主要方法

package com.android10;import java.io.IOException;import java.io.InputStream;import android.app.Activity;import android.os.Bundle;import com.thoughtworks.xstream.XStream;public class MainActivity extends Activity {    @Override    public void onCreate(Bundle savedInstanceState)  {        super.onCreate(savedInstanceState);        setContentView( R.layout.activity_main );        //得到資源中的資料流          String fileName = "aa.xml" ; //檔案名稱字           try {            InputStream in = getResources().getAssets().open( fileName ) ;            XStream xstream = new XStream() ;               //這個blog標識一定要和Xml中的保持一直,否則會報錯                xstream.alias( "blog" , Product.class );             Product product = (Product) xstream.fromXML( in );            System.out.println("sss " + product.getName() + product.getAge()  );        } catch (IOException e) {            e.printStackTrace();        }      }}


4、運行結果

 product jhon30 person  saliy36

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.