02_Android写xml文件和读xml文件

简介: 新建Android项目编写AndroidManifest.xml,使本Android项目具有单元测试功能和写外设的权限。 <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"

  1. 新建Android项目

  2. 编写AndroidManifest.xml,使本Android项目具有单元测试功能和写外设的权限。

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.itheima28.xmldemo"

    android:versionCode="1"

    android:versionName="1.0" >

 

    <uses-sdk

        android:minSdkVersion="8"

        android:targetSdkVersion="19" />

   

    <!—用于单元测试—>

    <instrumentation

        android:name="android.test.InstrumentationTestRunner"

        android:targetPackage="com.itheima28.xmldemo">

    </instrumentation>

   

    <!—写外设的权限à

    <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" >

        <!—单元测试所需à

        <uses-library android:name="android.test.runner"/>

       

        <activity

            android:name="com.itheima28.xmldemo.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>

 

3 Person对象

package com.itheima28.xmldemo;

 

public class Person {

 

    private int id;

    private String name;

    private int age;

 

    @Override

    public String toString() {

       return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";

    }

    public Person() {

       super();

    }

    public Person(int id, String name, int age) {

       super();

       this.id = id;

       this.name = name;

       this.age = age;

    }

    public int getId() {

       return id;

    }

    public void setId(int id) {

       this.id = id;

    }

    public String getName() {

       return name;

    }

    public void setName(String name) {

       this.name = name;

    }

    public int getAge() {

       return age;

    }

    public void setAge(int age) {

       this.age = age;

    }

 

}

4 xml文件和读xml文件的代码

package com.itheima28.xmldemo.test;

 

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.util.ArrayList;

import java.util.List;

 

import org.xmlpull.v1.XmlPullParser;

import org.xmlpull.v1.XmlSerializer;

 

import android.os.Environment;

import android.test.AndroidTestCase;

import android.util.Log;

import android.util.Xml;

 

import com.itheima28.xmldemo.Person;

 

public class TestCase extends AndroidTestCase {

 

         /**

          * 测试写xml文件

          */

         public void testWriteXml() {

                   writeXmlToLocal();

         }

        

         /**

          * 测试读xml文件

          */

         public void testReadXml() {

                   List<Person> personList = parseXmlFromLocal();

                   for (Person person : personList) {

                            Log.i("TestCase",person.toString());

                   }

         }

        

         /**

          * xml文件到本地

          */

         private void writeXmlToLocal() {

                   List<Person> personList = getPersonList();

                  

                   //获得序列化对象

                   XmlSerializer serializer = Xml.newSerializer();

                  

                   try {

                            //测试获得到的位置是:/storage/emulated/0

                            File path = new File(Environment.getExternalStorageDirectory(),"persons.xml");

                       FileOutputStream fos = new FileOutputStream(path);

                       //指定序列化对象输出的位置和编码

                       serializer.setOutput(fos,"utf-8");

                       //写开始<?xml version='1.0' encoding='utf-8' standalone='yes' ?>

                       serializer.startDocument("utf-8", true);

                      

                       //<persons>

                       serializer.startTag(null, "persons");

                       for (Person person : personList) {

                                     //开始写入

                                serializer.startTag(null, "person");

                                serializer.attribute(null, "id", String.valueOf(person.getId()));

                               

                                //写名字<name>

                                serializer.startTag(null, "name");

                                serializer.text(person.getName());

                                //</name>

                serializer.endTag(null, "name");

               

                //写年龄

                //<age>

                serializer.startTag(null, "age");

                serializer.text(String.valueOf(person.getAge()));

                //</age>

                serializer.endTag(null, "age");

               

                //</persons>

                serializer.endTag(null, "person");

                       }

                      

                       //</persons>

            serializer.endTag(null, "persons");

                      

            //结束

            serializer.endDocument();

                   } catch (Exception e) {

                            e.printStackTrace();

                   }

         }

        

         /**

          * 用于生成一个ListPerson集合

          * @return

          */

         private List<Person> getPersonList() {

                   List<Person> personList = new ArrayList<Person>();

                  

                   for (int i = 0; i < 30; i++) {

                            personList.add(new Person(i,"wang" + i, 18 + i));

                   }

                  

                   return personList;

         }

        

         /**

          * 解析xml文件并将xml文件中内容写List集合中

          * @return

          */

         private List<Person> parseXmlFromLocal() {

                   try {

                            File path = new File(Environment.getExternalStorageDirectory(),"persons.xml");

                            FileInputStream fis = new FileInputStream(path);

                           

                            //获得pull解析器对象

                            XmlPullParser parser = Xml.newPullParser();

                            //指定解析的文件的编码格式

                            parser.setInput(fis,"utf-8");

                           

                            //获得时间类型

                            int eventType = parser.getEventType();

                           

                            List<Person> personList = null;

                            Person person = null;

                            String id;

                           

                            while (eventType != XmlPullParser.END_DOCUMENT) {

                                     //获取当前节点的名称

                                     String tagName = parser.getName();

                                    

                                     switch (eventType) {

                                     //获得当前节点的名称 <person>

                                     case XmlPullParser.START_TAG:

                                               //<persons>

                                               if("persons".equals(tagName)) {

                                                        personList = new ArrayList<Person>();

                                               } else if ("person".equals(tagName)) { //<person id="1">

                                                        person = new Person();

                                                        id = parser.getAttributeValue(null,"id");

                                                        person.setId(Integer.valueOf(id));

                                               } else if("name".equals(tagName)) {

                                                        person.setName(parser.nextText());

                                               } else if("age".equals(tagName)) { //<age>

                                                        person.setAge(Integer.parseInt(parser.nextText()));

                                               }

                                               break;

                                     //</persons>

                                     case XmlPullParser.END_TAG:

                                               if ("person".equals(tagName)) {

                                                        //需要把上面设置好的person对象添加到集合中

                                                        personList.add(person);

                                               }

                                               break;

                                     default:

                                               break;

                                     }

                                    

                                     //获得下一个事件类型

                                     eventType = parser.next();

                            }

                            return personList;

                   } catch (Exception e) {

                            e.printStackTrace();

                   }

                   return null;

         }

}

5 设置Log过滤器

6、控制台输出结果

 

 

 

 

 

 

 

 

 

 

 

目录
相关文章
|
2月前
|
XML 前端开发 Java
讲解SSM的xml文件
本文详细介绍了SSM框架中的xml配置文件,包括springMVC.xml和applicationContext.xml,涉及组件扫描、数据源配置、事务管理、MyBatis集成以及Spring MVC的视图解析器配置。
70 1
|
2月前
|
ARouter Android开发
Android不同module布局文件重名被覆盖
Android不同module布局文件重名被覆盖
|
4月前
|
Java Android开发 C++
Android Studio JNI 使用模板:c/cpp源文件的集成编译,快速上手
本文提供了一个Android Studio中JNI使用的模板,包括创建C/C++源文件、编辑CMakeLists.txt、编写JNI接口代码、配置build.gradle以及编译生成.so库的详细步骤,以帮助开发者快速上手Android平台的JNI开发和编译过程。
321 1
|
4月前
|
XML Java 数据格式
Spring5入门到实战------7、IOC容器-Bean管理XML方式(外部属性文件)
这篇文章是Spring5框架的实战教程,主要介绍了如何在Spring的IOC容器中通过XML配置方式使用外部属性文件来管理Bean,特别是数据库连接池的配置。文章详细讲解了创建属性文件、引入属性文件到Spring配置、以及如何使用属性占位符来引用属性文件中的值。
Spring5入门到实战------7、IOC容器-Bean管理XML方式(外部属性文件)
|
27天前
|
XML Android开发 数据格式
Eclipse 创建 XML 文件
Eclipse 创建 XML 文件
25 2
|
1月前
|
Java Maven
maven项目的pom.xml文件常用标签使用介绍
第四届人文,智慧教育与服务管理国际学术会议(HWESM 2025) 2025 4th International Conference on Humanities, Wisdom Education and Service Management
107 8
|
2月前
|
XML JavaScript Java
java与XML文件的读写
java与XML文件的读写
27 3
|
2月前
|
ARouter Android开发
Android不同module布局文件重名被覆盖
Android不同module布局文件重名被覆盖
146 0
|
2月前
|
XML 存储 缓存
C#使用XML文件的详解及示例
C#使用XML文件的详解及示例
110 0
|
2月前
|
XML 存储 Web App开发
查看 XML 文件
查看 XML 文件