DOM解析原理是把xml文件的各種部分都看成是節點,所有的節點因為層級關系最後形成了一顆節點樹。而DOM的解析方式便是在內存中生存這棵樹,並允許用戶進行相關的操作。
一、設計界面
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數據(DOM)" />
-
- <Button
- android:id="@+id/read"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="讀取XML數據(DOM)" />
-
- </LinearLayout>
二、程序文件
打開“src/com.genwoxue.filedom/MainActivity.java”文件。
然後輸入以下代碼:
[java] view plain copy
- package com.genwoxue.filedom;
-
-
- import java.io.File;
- import java.io.IOException;
-
- import javax.xml.parsers.DocumentBuilder;
- import javax.xml.parsers.DocumentBuilderFactory;
- import javax.xml.parsers.ParserConfigurationException;
- import javax.xml.transform.OutputKeys;
- import javax.xml.transform.Transformer;
- import javax.xml.transform.TransformerConfigurationException;
- import javax.xml.transform.TransformerException;
- import javax.xml.transform.TransformerFactory;
- import javax.xml.transform.dom.DOMSource;
- import javax.xml.transform.stream.StreamResult;
-
- import org.w3c.dom.Document;
- import org.w3c.dom.Element;
- import org.w3c.dom.NodeList;
- import org.xml.sax.SAXException;
-
- 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";
-
- @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)
- {
-
- DocumentBuilder builder=null;
- Document doc=null;
- Transformer trans=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();
-
- //實例化DocumentBuilderFactory
- DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
- //獲取DocumentBuilder對象
- try {
- builder=factory.newDocumentBuilder();
- } catch (ParserConfigurationException e) {
- e.printStackTrace();
- }
- //獲取Document對象
- doc=builder.newDocument();
- //建立節點
- Element books=doc.createElement("books");
- Element book=doc.createElement("book");
- Element bookname=doc.createElement("bookname");
- Element author=doc.createElement("author");
- Element publisher=doc.createElement("publisher");
-
- //添加內容
- bookname.appendChild(doc.createTextNode("跟我學Android"));
- author.appendChild(doc.createTextNode("蔣老夫子"));
- publisher.appendChild(doc.createTextNode("人民郵電出版社"));
-
- //設置節點關系
- book.appendChild(bookname);
- book.appendChild(author);
- book.appendChild(publisher);
-
- books.appendChild(book);
- doc.appendChild(books);
-
- //輸出到文件
- TransformerFactory transfactory=TransformerFactory.newInstance();
-
- try {
- trans=transfactory.newTransformer();
- } catch (TransformerConfigurationException e) {
- e.printStackTrace();
- }
-
- trans.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
- DOMSource source=new DOMSource(doc);
- StreamResult result=new StreamResult(file);
-
- try {
- trans.transform(source, result);
- } catch (TransformerException e) {
- e.printStackTrace();
- }
- }
- });
-
- btnRead.setOnClickListener(new OnClickListener(){
- public void onClick(View v)
- {
- DocumentBuilder builder=null;
- Document doc=null;
- StringBuffer info=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);
-
- if(!file.exists()){
- Toast.makeText(getApplicationContext(), "文件不存在!", Toast.LENGTH_LONG).show();
- return;
- }
-
- //實例化DocumentBuilderFactory
- DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
- //獲取DocumentBuilder對象
- try {
- builder=factory.newDocumentBuilder();
- } catch (ParserConfigurationException e) {
- e.printStackTrace();
- }
-
- //獲取Document對象
- try {
- doc=builder.parse(file);
- } catch (SAXException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- //查找book節點
- NodeList nodelist=doc.getElementsByTagName("book");
-
- //獲取節點文本內容
- info=new StringBuffer();
-
- for(int i=0;i<nodelist.getLength();i++){
- Element element=(Element)nodelist.item(i);
- info.append(info+element.getElementsByTagName("bookname").item(0).getFirstChild().getNodeValue()).append("☆☆☆");
- info.append(element.getElementsByTagName("author").item(0).getFirstChild().getNodeValue()).append("☆☆☆");
- info.append(element.getElementsByTagName("publisher").item(0).getFirstChild().getNodeValue()).append("☆☆☆");
- }
-
- Toast.makeText(getApplicationContext(), info.toString(), Toast.LENGTH_LONG).show();
- }
- });
- }
- }
三、配置文件
打開“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.filedom"
- android:versionCode="1"
- android:versionName="1.0" >
-
- <uses-sdk
- android:minSdkVersion="8"
- android:targetSdkVersion="15" />
- <strong><span style="color:#ff0000;"><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
- </span></strong>
- <application
- android:allowBackup="true"
- android:icon="@drawable/ic_launcher"
- android:label="@string/app_name"
- android:theme="@style/AppTheme" >
- <activity
- android:name="com.genwoxue.filedom.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" />
四、運行結果