Android XML解析、序列化demo

本文介绍如何在Android应用中获取系统内存容量、使用SharedPreferences进行数据存储与读取、XML文件的序列化与解析,以及自定义XML数据的保存与获取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有4个小例子:

1.分别是获取系统内存容量、

2.使用SharedPreferences方式读写操作

3.使用XmlSerializer序列号XML文件

4.使用XmlPullParser解析XML文件

package com.gj.save;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;

import org.xmlpull.v1.XmlSerializer;

import com.gj.save.bean.User;

import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Environment;
import android.util.Xml;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;

public class MainActivity extends Activity {
	TextView tv;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		tv = (TextView) findViewById(R.id.tv);
	}
	public void save(View v){
		Toast.makeText(this, MyUtils.getSDAvailableStorageSpace(this), 1).show();
	}
	
	public void save1(View v){
		Toast.makeText(this, MyUtils.getSysAvailableStorageSpace(this), 1).show();
	}
	/**
	 * 使用SharedPreferences保存XML格式数据
	 * @param v
	 */
	public void save2(View v){
		//在data/data/包/shared_prefs目录下创建info.xml
		SharedPreferences sp = getSharedPreferences("info", MODE_PRIVATE);
		Editor edit = sp.edit();
		edit.putInt("id", 1);
		edit.putBoolean("sex", false);
		edit.putString("name", "zhangsan");
		edit.commit();
	}
	/**
	 * 使用SharedPreferences方式读取数据
	 * @param v
	 */
	public void save3(View v){
		//MODE_PRIVATE,私有文件
		SharedPreferences sp = getSharedPreferences("info", MODE_PRIVATE);
		//getString()第二个参数为缺省值,如果preference中不存在该key,将返回缺省值
		String name = sp.getString("name", "");
		Toast.makeText(this, "id:"+sp.getInt("id", 1)+"\tsex:"+sp.getBoolean("sex", true)+"\tname:"+sp.getString("name", ""), 1).show();
	}
	/**
	 * XML文件序列化
	 * @param v
	 */
	public void save4(View v){
		try {
			XmlSerializer serializer = Xml.newSerializer();
			//getExternalStorageDirectory在SD卡下生成
			File file = new File(Environment.getExternalStorageDirectory(),"backup.xml");
			FileOutputStream fos = new FileOutputStream(file);
			serializer.setOutput(fos, "utf-8");
			serializer.startDocument("utf-8", true);
			serializer.startTag(null, "users");
				/**------------------------*/
				serializer.startTag(null, "user");
				serializer.attribute(null, "id", 1+"");
					/**------------------------*/
					serializer.startTag(null, "name");
					serializer.text("zhangsan");
					serializer.endTag(null, "name");
					/**------------------------*/
					serializer.startTag(null, "age");
					serializer.text("28");
					serializer.endTag(null, "age");
					/**------------------------*/
				serializer.endTag(null, "user");
				/**------------------------*/
			serializer.endTag(null, "users");
			serializer.endDocument();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void save5(View v){
		//从ClassLoader中获取class包下的文件
		InputStream is = MainActivity.this.getClassLoader().getResourceAsStream("users.xml");
		try {
			StringBuffer sb = new StringBuffer();
			List<User> list = UserService.getUsers(is);
			for (User user : list) {
				sb.append(user.toString());
			}
			tv.setText(sb.toString());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Toast.makeText(this, "解析失败", 1).show();
		}
	}
}

package com.gj.save;

import java.io.File;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.text.format.Formatter;

@SuppressLint("NewApi")
public class MyUtils {

	/**
	 * 得到SD卡总容量
	 * @param context
	 * @return
	 */
	@SuppressLint("NewApi")
	public static String getSDTotalStorageSpace(Context context){
		File path = Environment.getExternalStorageDirectory();
		StatFs fs = new StatFs(path.getPath());
		long blockSize = fs.getBlockSizeLong();
		long totalBlocks = fs.getBlockCountLong();
		long totalSize = blockSize*totalBlocks;
		return Formatter.formatFileSize(context, totalSize);
	}
	/**
	 * 得到SD卡可用容量
	 * @param context
	 * @return
	 */
	@SuppressLint("NewApi")
	public static String getSDAvailableStorageSpace(Context context){
		File path = Environment.getExternalStorageDirectory();
		StatFs fs = new StatFs(path.getPath());
		long blockSize = fs.getBlockSizeLong();
		long availableBlocks = fs.getAvailableBlocksLong();
		long availSize = availableBlocks*blockSize;
		return Formatter.formatFileSize(context, availSize);
	}
	
	/**
	 * 得到系统总容量
	 * @param context
	 * @return
	 */
	@SuppressLint("NewApi")
	public static String getSysTotalStorageSpace(Context context){
		File path = Environment.getDataDirectory();
		StatFs fs = new StatFs(path.getPath());
		long blockSize = fs.getBlockSizeLong();
		long totalBlocks = fs.getBlockCountLong();
		long totalSize = blockSize*totalBlocks;
		return Formatter.formatFileSize(context, totalSize);
	}
	/**
	 * 得到系统可用容量
	 * @param context
	 * @return
	 */
	@SuppressLint("NewApi")
	public static String getSysAvailableStorageSpace(Context context){
		File path = Environment.getDataDirectory();
		StatFs fs = new StatFs(path.getPath());
		long blockSize = fs.getBlockSizeLong();
		long availableBlocks = fs.getAvailableBlocksLong();
		long availSize = availableBlocks*blockSize;
		return Formatter.formatFileSize(context, availSize);
	}
}

package com.gj.save;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.util.Xml;

import com.gj.save.bean.User;

public class UserService {

	public static List<User> getUsers(InputStream is) throws Exception{
		//得到XmlPullParser解析器
		XmlPullParser pull =  Xml.newPullParser();
		List<User> list = null;
		User user = null;
		pull.setInput(is, "utf-8");
		//得到当前标示
		int type = pull.getEventType();
		//如果标示不是结束标示就循环
		while(XmlPullParser.END_DOCUMENT != type){
			switch (type) {
				case XmlPullParser.START_TAG:
					if("users".equals(pull.getName())){
						list = new ArrayList<User>();
					}else if("user".equals(pull.getName())){
						user = new User();
						user.setId(pull.getAttributeValue(0));
					}else if("name".equals(pull.getName())){
						user.setName(pull.nextText());
					}else if("age".equals(pull.getName())){
						user.setAge(pull.nextText());
					}else if("birth".equals(pull.getName())){
						user.setBirth(pull.nextText());
					}else if("sex".equals(pull.getName())){
						user.setSex(pull.nextText());
					}
					break;	
				case XmlPullParser.END_TAG:
					if("user".equals(pull.getName())){
						list.add(user);
						user = null;
					}
					break;		
				default:
					break;
			}
			//将"游标"指到下一行
			type = pull.next();
		}
		return list;
	}
}

package com.gj.save.bean;

public class User {
	private String id;
	private String name;
	private String age;
	private String birth;
	private String sex;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	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 String getBirth() {
		return birth;
	}
	public void setBirth(String birth) {
		this.birth = birth;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	@Override
	public String toString() {
		return "[ID=" + id + ", 姓名=" + name + ", 年龄=" + age
				+ ", 生日=" + birth + ", 性别=" + sex + "]\n";
	}
}

<?xml version='1.0' encoding='utf-8'?>
<users>
	<user id="1">
		<name>zhangsan</name>
		<age>23</age>
		<birth>1991-10-12</birth>
		<sex>男</sex>
	</user>
	<user id="2">
		<name>李四</name>
		<age>25</age>
		<birth>1983-12-11</birth>
		<sex>女</sex>
	</user>
	<user id="3">
		<name>赵五</name>
		<age>61</age>
		<birth>1951-09-11</birth>
		<sex>男</sex>
	</user>
	<user id="4">
		<name>妹纸</name>
		<age>18</age>
		<birth>1993-02-22</birth>
		<sex>女</sex>
	</user>
</users>

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.gj.save.MainActivity"
    tools:ignore="MergeRootFrame" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <Button
            android:id="@+id/button1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="save"
            android:text="得到SD卡可用容量" />

        <Button
            android:id="@+id/button16"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="save1"
            android:text="得到系统可用容量" />

        <Button
            android:id="@+id/button2"
             android:onClick="save2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="保存XML" />
        
        <Button
            android:id="@+id/button2"
             android:onClick="save3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="获取XML内容" />
        
        <Button
            android:id="@+id/button2"
             android:onClick="save4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="保存自定义XML" />
		<Button
            android:id="@+id/button4"
             android:onClick="save5"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="pull解析XML" />
		
        <TextView
            android:id="@+id/tv"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="" />

    </LinearLayout>

</FrameLayout>

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.gj.save"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="19" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.gj.save.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值