在android系統中,很多資源文件中,很多都是xml格式,在android系統中解析這些xml的方式,是使用pul解析器進行解析的,它和sax解析一樣(個人感覺要比sax簡單點),也是采用事件驅動進行解析的,當pull解析器,開始解析之後,我們可以調用它的next()方法,來獲取下一個解析事件(就是開始文檔,結束文檔,開始標簽,結束標簽),當處於某個元素時可以調用XmlPullParser的getAttributte()方法來獲取屬性的值,也可調用它的nextText()獲取本節點的值。
一、設計界面
1、布局文件
打開activity_main.xml文件。
輸入以下代碼:
[html] view plain copy
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
-
- <Button
- android:id="@+id/save"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="保存XML文件(XMLPull)" />
-
- <Button
- android:id="@+id/read"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="讀取XML文件(XMLPull)" />
-
- </LinearLayout>
二、程序文件
1、新建“Book.java”文件
[java] view plain copy
- package com.genwoxue.filexmlpull;
-
- public class Book{
- private String bookName;
- private String author;
- private String publisher;
-
- //設置書名
- public void setBookName(String name){
- this.bookName=name;
- }
-
- //獲取書名
- public String getBookName(){
- return bookName;
- }
-
- //設置作者
- public void setAuthor(String author){
- this.author=author;
- }
-
- //獲取作者
- public String getAuthor(){
- return author;
- }
-
- //設置出版社
- public void setPublisher(String publisher){
- this.publisher=publisher;
- }
-
- //獲取出版社
- public String getPublisher(){
- return publisher;
- }
-
- }
2、新建“XmlPullSave.java”文件
[java] view plain copy
- package com.genwoxue.filexmlpull;
-
- import java.io.OutputStream;
- import java.util.Iterator;
- import java.util.List;
- import org.xmlpull.v1.XmlPullParserFactory;
- import org.xmlpull.v1.XmlSerializer;
-
- public class XmlPullSave {
- private OutputStream ouput=null;
- private List<Book> books=null;
- //構造函數
- public XmlPullSave(OutputStream ouput,List<Book> books){
- this.ouput=ouput;
- this.books=books;
- }
-
- public void saveBooks() throws Exception{
-
- //實例化工廠類XmlPullParserFactory
- XmlPullParserFactory factory=XmlPullParserFactory.newInstance();
- //創建XmlSerializer實例
- XmlSerializer xs=factory.newSerializer();
- xs.setOutput(this.ouput, "UTF-8");
- xs.startDocument("UTF-8", true);
- xs.startTag(null, "books");
- Iterator<Book> iterator=this.books.iterator();
- while(iterator.hasNext()){
- Book book=iterator.next();
- xs.startTag(null, "book");
- xs.startTag(null, "bookname");
- xs.text(book.getBookName());
- xs.endTag(null, "bookname");
- xs.startTag(null, "author");
- xs.text(book.getAuthor());
- xs.endTag(null, "author");
- xs.startTag(null, "publisher");
- xs.text(book.getPublisher());
- xs.endTag(null, "publisher");
- xs.endTag(null, "book");
- }
- xs.endTag(null, "books");
- xs.endDocument();
- xs.flush();
- }
-
- }
3、新建“XmlPull.java”文件
[java] view plain copy
- package com.genwoxue.filexmlpull;
-
- import java.io.InputStream;
- import java.util.ArrayList;
- import java.util.List;
- import org.xmlpull.v1.XmlPullParser;
- import org.xmlpull.v1.XmlPullParserFactory;
-
- public class XmlPull {
-
- private InputStream input=null;
-
- //構造函數
- public XmlPull(InputStream input){
- this.input=input;
- }
-
- public List<Book> getBooks() throws Exception{
- List<Book> books=null;
- Book book=null;
- //創建XmlPullParser,有兩種方式 (本案例采用方式一,方式二可自行嘗試)
- //方式一:使用工廠類XmlPullParserFactory
- XmlPullParserFactory factory=XmlPullParserFactory.newInstance();
- XmlPullParser parser=factory.newPullParser();
- //方式二:使用Android提供的實用工具類android.util.Xml
- //XmlPullParser parser = Xml.newPullParser();
- parser.setInput(this.input,"UTF-8");
- int eventType=parser.getEventType(); //獲取事件代碼
- while(eventType!=XmlPullParser.END_DOCUMENT){
- switch(eventType){
- case XmlPullParser.START_DOCUMENT: //判斷當前事件是否是文檔開始事件
- books=new ArrayList<Book>(); //初始化books集合
- break;
- case XmlPullParser.START_TAG: //判斷當前事件是否是標簽元素開始事件
- if("book".equals(parser.getName())) //判斷開始標簽元素是否是book
- book=new Book(); //初始化book對象
- if(book!=null){
- if("bookname".equals(parser.getName())) //判斷標簽元素是否是bookname
- book.setBookName(parser.nextText()); //parser.nextText()獲取bookname元素後文本
- else if("author".equals(parser.getName()))
- book.setAuthor(parser.nextText());
- else if("publisher".equals(parser.getName()))
- book.setPublisher(parser.nextText());
- }
- break;
- case XmlPullParser.END_TAG: //判斷當前事件是否是標簽元素結束事件
- if("book".equals(parser.getName())){ //判斷開始標簽元素是否是book
- books.add(book); //將book對像添加到books列表
- book=null; //book清空
- }
- break;
- }
- eventType=parser.next(); //獲取下一個事件代碼
- }
- return books; //返回books列表
- }
- }
4、打開“src/com.genwoxue.filesax/MainActivity.java”文件。
然後輸入以下代碼:
[java] view plain copy
- package com.genwoxue.filexmlpull;
-
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.util.ArrayList;
- import java.util.List;
- import android.os.Bundle;
- import android.os.Environment;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.Toast;
- import android.app.Activity;
-
- public class MainActivity extends Activity {
-
- private Button btnSave=null;
- private Button btnRead=null;
- private File file=null;
- private static final String FILENAME="book.xml";
- private StringBuffer info=null;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- btnSave=(Button)super.findViewById(R.id.save);
- btnRead=(Button)super.findViewById(R.id.read);
-
- btnSave.setOnClickListener(new OnClickListener(){
- public void onClick(View v)
- {
- OutputStream output=null;
- XmlPullSave xmlPullSave=null;
- //判斷外部存儲卡是否存在
- if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
- Toast.makeText(getApplicationContext(), "讀取失敗,SD存儲卡不存在!", Toast.LENGTH_LONG).show();
- return;
- }
-
- //初始化File
- String path=Environment.getExternalStorageDirectory().toString()
- +File.separator
- +"genwoxue"
- +File.separator
- +FILENAME;
- file=new File(path);
-
- //如果當前文件的父文件夾不存在,則創建genwoxue文件夾
- if(!file.getParentFile().exists())
- file.getParentFile().mkdirs();
-
- //初始化books
- List<Book> books=new ArrayList<Book>();
- Book book=new Book();
- book.setBookName("跟我學Android");
- book.setAuthor("蔣老夫子");
- book.setPublisher("人民郵電出版社");
- books.add(book);
- book=null;
- book=new Book();
- book.setBookName("從零開始學Android");
- book.setAuthor("蔣老夫子");
- book.setPublisher("清華大學出版社");
- books.add(book);
- book=null;
-
- //保存XML文件
- try {
- output=new FileOutputStream(file);
- xmlPullSave=new XmlPullSave(output,books); //初始化XmlPullSave
- try {
- xmlPullSave.saveBooks(); //saveBooks保存至XML文件
- } catch (Exception e) {
- e.printStackTrace();
- }
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- }finally{
- if(output!=null)
- try {
- output.close();
- books.clear();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- });
-
- btnRead.setOnClickListener(new OnClickListener(){
- public void onClick(View v)
- {
- info=new StringBuffer();
- //判斷外部存儲卡是否存在
- if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
- Toast.makeText(getApplicationContext(), "讀取失敗,SD存儲卡不存在!", Toast.LENGTH_LONG).show();
- return;
- }
- //判斷文件是否存在
- String path=Environment.getExternalStorageDirectory().toString()
- +File.separator
- +"genwoxue"
- +File.separator
- +FILENAME;
- file=new File(path);
-
- if(!file.exists()){
- Toast.makeText(getApplicationContext(), "XML文件不存在!", Toast.LENGTH_LONG).show();
- return;
- }
-
- //解析XML文件
- try {
- InputStream input=new FileInputStream(file);
- XmlPull pull=new XmlPull(input);
- List<Book> list=pull.getBooks();
-
- //遍歷列表,獲取書籍信息
- for(int pos=0;pos<list.size();pos++){
- info.append(list.get(pos).getBookName()).append("☆☆☆");
- info.append(list.get(pos).getAuthor()).append("☆☆☆");
- info.append(list.get(pos).getPublisher()).append("☆☆☆");
- }
- }catch(Exception e){
- e.printStackTrace();
- }
-
- Toast.makeText(getApplicationContext(), info.toString(), Toast.LENGTH_LONG).show();
- }
- });
- }
- }
- <p></p><p><strong></strong>
- </p>
三、配置文件
打開“AndroidManifest.xml”文件。
然後輸入以下代碼:
[html] view plain copy
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.genwoxue.filexmlpull"
- android:versionCode="1"
- android:versionName="1.0" >
-
- <uses-sdk
- android:minSdkVersion="8"
- android:targetSdkVersion="15" />
- <span style="color:#ff0000;"><strong><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/></strong>
- </span>
- <application
- android:allowBackup="true"
- android:icon="@drawable/ic_launcher"
- android:label="@string/app_name"
- android:theme="@style/AppTheme" >
- <activity
- android:name="com.genwoxue.filexmlpull.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>
注意:由於要進行讀寫外部存儲卡操作,故而需要在AndroidManifest.xml文件中添加兩項權限:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
四、運行結果