android XMl 解析神奇xstream 六: 把集合list 轉化為 XML文檔,androidxstream

來源:互聯網
上載者:User

android XMl 解析神奇xstream 六: 把集合list 轉化為 XML文檔,androidxstream

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

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

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

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

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

android XMl 解析神奇xstream 五: 把複雜物件轉換成 xml ,並寫入SD卡中的xml檔案

 

1、建立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;    }}

 

package com.android10;import java.util.List;public class ListBean {    private List<Product> root ;    public List<Product> getRoot() {        return root;    }    public void setRoot(List<Product> root) {        this.root = root;    }}


2、主要方法

 

package com.android10;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.util.ArrayList;import java.util.List;import javax.xml.transform.OutputKeys;import javax.xml.transform.Source;import javax.xml.transform.Transformer;import javax.xml.transform.sax.SAXSource;import javax.xml.transform.sax.SAXTransformerFactory;import javax.xml.transform.stream.StreamResult;import org.xml.sax.InputSource;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 );        XStream xstream = new XStream() ;        List<Product> root = getList() ;        //將ListBean中的集合設定空元素,即不顯示集合元素標籤        xstream.addImplicitCollection( ListBean.class, "root");        xstream.autodetectAnnotations(true);                //設定別名        xstream.alias( "product", Product.class );        //將name設定為父類(Student)的元素的屬性        xstream.useAttributeFor( Product.class, "name" );        //把list集合轉換成Xml字串        String xmlString =  xstream.toXML(  root ) ;        //把Xml字串寫入SD卡Xml檔案        XstreamUtil xstreamUtil = new XstreamUtil() ;        xstreamUtil.writeToXml( this ,  xmlString ) ;        //把Xml字串轉化成list集合        List<Product> list = new ArrayList<Product>() ;        list =  (List<Product>) xstream.fromXML( xmlString ) ;        System.out.println("sss"+  formatXml( xmlString ) );    }    /**     * 得到資料     * @return     */    private List<Product>  getList(){        Person person1 = new Person() ;        person1.setpName( "saliy" ) ;        person1.setpAge( "36" );        Product product1 = new Product() ;        product1.setName( "jhon" ) ;        product1.setAge( "30" );        product1.setPerson( person1 );        Person person2 = new Person() ;        person2.setpName( "saliy02" ) ;        person2.setpAge( "3602" );        Product product2 = new Product() ;        product2.setName( "jhon02" ) ;        product2.setAge( "3002" );        product2.setPerson( person2 );        List<Product> root = new ArrayList<Product>() ;        root.add( product1 ) ;        root.add( product2 ) ;        return root ;    }    /**     * 格式化XML字串     * @param xml     * @return     */    public static String formatXml(String xml){        try{            Transformer serializer= SAXTransformerFactory.newInstance().newTransformer();            serializer.setOutputProperty(OutputKeys.INDENT, "yes");            serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");            Source xmlSource=new SAXSource(new InputSource(new ByteArrayInputStream(xml.getBytes())));            StreamResult res =  new StreamResult(new ByteArrayOutputStream());                        serializer.transform(xmlSource, res);            return new String(((ByteArrayOutputStream)res.getOutputStream()).toByteArray());        }catch(Exception e){                     return xml;        }    }}

 

package com.android10;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStreamWriter;import android.content.Context;import android.os.Environment;public class XstreamUtil {    XcallBack xcallBack ;    /**     * 把xml字串寫入SD卡檔案     * @param context     * @param str  xml字串     */    public void writeToXml(Context context, String str ){          //擷取檔案路徑        String SDPATH = Environment.getExternalStorageDirectory()  + "/myfile1.xml/" ;        //建立檔案        File file = new File( SDPATH ) ;        if( !file.exists() ){            try {                file.createNewFile() ;            } catch (IOException e) {                e.printStackTrace();            }         }        //寫入資料        try {            FileOutputStream out = new FileOutputStream( file ) ;            OutputStreamWriter outw = new OutputStreamWriter(out);              try {                  outw.write(str);                  outw.close();                  out.close();                  if( xcallBack != null ){                    xcallBack.success();                 }            } catch (IOException e) {                 if( xcallBack != null ){                    xcallBack.fail();                 }            }          } catch (FileNotFoundException e1) {            e1.printStackTrace();            if( xcallBack != null ){                xcallBack.fail();             }        }    }     //設定監聽器    void setXStreamLister( XcallBack xcallBack ){        this.xcallBack = xcallBack ;    }}interface XcallBack{    /**     * 寫入成功     */    void success() ;      /**     * 寫入失敗     */    void fail() ;     }

 

3、運行結果

<list>
  <product name="jhon">
    <age>30</age>
    <person>
      <pAge>36</pAge>
      <pName>saliy</pName>
    </person>
  </product>
  <product name="jhon02">
    <age>3002</age>
    <person>
      <pAge>3602</pAge>
      <pName>saliy02</pName>
    </person>
  </product>
</list>

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.