android XMl 解析神奇xstream 六: 把集合list 转化为 XML文档

简介: 前言:对xstream不理解的请看: android XMl 解析神奇xstream 一: 解析android项目中 asset 文件夹 下的 aa.xml 文件 android XMl 解析神奇xstream 二: 把对象转换成xml android XMl 解析神奇xstream 三:...
前言:对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>

 

相关文章
|
3天前
|
XML API PHP
Android使用XML-RPC实现blog客户端
Android使用XML-RPC实现blog客户端
|
3天前
|
存储 安全 算法
Java一分钟之-Java集合框架入门:List接口与ArrayList
【5月更文挑战第10天】本文介绍了Java集合框架中的`List`接口和`ArrayList`实现类。`List`是有序集合,支持元素重复并能按索引访问。核心方法包括添加、删除、获取和设置元素。`ArrayList`基于动态数组,提供高效随机访问和自动扩容,但非线程安全。文章讨论了三个常见问题:索引越界、遍历时修改集合和并发修改,并给出避免策略。通过示例代码展示了基本操作和安全遍历删除。理解并正确使用`List`和`ArrayList`能提升程序效率和稳定性。
7 0
|
3天前
|
Android开发
android string.xml文件中的整型和string型代替
android string.xml文件中的整型和string型代替
|
1月前
|
存储 Java API
java集合Collection(List)和泛型
java集合Collection(List)和泛型
|
1月前
|
算法
递归淘汰List集合头部数据,获取最终集合的起始坐标
递归淘汰List集合头部数据,获取最终集合的起始坐标
|
1月前
|
Java
list集合 使用java8同一列表获取前一条的数据放到当前对象中
list集合 使用java8同一列表获取前一条的数据放到当前对象中
|
1月前
|
XML Android开发 数据格式
Caused by: android.view.InflateException: Binary XML file line #11: Error inflating class
Caused by: android.view.InflateException: Binary XML file line #11: Error inflating class
23 0
|
1月前
|
存储 安全 Java
Java集合详解(List、Map、Set)
Java集合详解(List、Map、Set)
34 4
|
2月前
|
XML 数据格式
android.view.InflateException: Binary XML file line #0: Attempt to invoke virtual
android.view.InflateException: Binary XML file line #0: Attempt to invoke virtual
10 0
|
2月前
|
存储 安全 Java
Python教程第3章 | 集合(List列表、Tuple元组、Dict字典、Set)
Python 列表、无序列表、字典、元组增删改查基本用法和注意事项
52 1