Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android技術基礎 >> 第62章、XML文件-DOM操作(從零開始學Android)

第62章、XML文件-DOM操作(從零開始學Android)

編輯:Android技術基礎

DOM解析原理是把xml文件的各種部分都看成是節點,所有的節點因為層級關系最後形成了一顆節點樹。而DOM的解析方式便是在內存中生存這棵樹,並允許用戶進行相關的操作。

一、設計界面

1、布局文件

打開activity_main.xml文件。

輸入以下代碼:

[html] view plain copy  
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout   
  3.     xmlns:android="http://schemas.android.com/apk/res/android"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent"  
  6.     android:orientation="vertical" >  
  7.   
  8.     <Button  
  9.         android:id="@+id/save"  
  10.         android:layout_width="wrap_content"  
  11.         android:layout_height="wrap_content"  
  12.         android:text="保存XML數據(DOM)" />  
  13.       
  14.     <Button  
  15.         android:id="@+id/read"  
  16.         android:layout_width="wrap_content"  
  17.         android:layout_height="wrap_content"  
  18.         android:text="讀取XML數據(DOM)" />  
  19.   
  20. </LinearLayout>  


二、程序文件

打開“src/com.genwoxue.filedom/MainActivity.java”文件。

然後輸入以下代碼:

[java] view plain copy  
  1. package com.genwoxue.filedom;  
  2.   
  3.   
  4. import java.io.File;  
  5. import java.io.IOException;  
  6.   
  7. import javax.xml.parsers.DocumentBuilder;  
  8. import javax.xml.parsers.DocumentBuilderFactory;  
  9. import javax.xml.parsers.ParserConfigurationException;  
  10. import javax.xml.transform.OutputKeys;  
  11. import javax.xml.transform.Transformer;  
  12. import javax.xml.transform.TransformerConfigurationException;  
  13. import javax.xml.transform.TransformerException;  
  14. import javax.xml.transform.TransformerFactory;  
  15. import javax.xml.transform.dom.DOMSource;  
  16. import javax.xml.transform.stream.StreamResult;  
  17.   
  18. import org.w3c.dom.Document;  
  19. import org.w3c.dom.Element;  
  20. import org.w3c.dom.NodeList;  
  21. import org.xml.sax.SAXException;  
  22.   
  23. import android.os.Bundle;  
  24. import android.os.Environment;  
  25. import android.view.View;  
  26. import android.view.View.OnClickListener;  
  27. import android.widget.Button;  
  28. import android.widget.Toast;  
  29. import android.app.Activity;  
  30.   
  31. public class MainActivity extends Activity {  
  32.   
  33.     private Button btnSave=null;  
  34.     private Button btnRead=null;  
  35.     private File file=null;  
  36.       
  37.     private static final String FILENAME="book.xml";  
  38.       
  39.     @Override  
  40.     protected void onCreate(Bundle savedInstanceState) {  
  41.         super.onCreate(savedInstanceState);  
  42.         setContentView(R.layout.activity_main);  
  43.         btnSave=(Button)super.findViewById(R.id.save);  
  44.         btnRead=(Button)super.findViewById(R.id.read);  
  45.           
  46.         btnSave.setOnClickListener(new OnClickListener(){  
  47.             public void onClick(View v)  
  48.             {    
  49.   
  50.                 DocumentBuilder builder=null;  
  51.                 Document doc=null;  
  52.                 Transformer trans=null;  
  53.                   
  54.                 //判斷外部存儲卡是否存在  
  55.                 if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){  
  56.                     Toast.makeText(getApplicationContext(), "讀取失敗,SD存儲卡不存在!", Toast.LENGTH_LONG).show();    
  57.                     return;  
  58.                 }  
  59.                   
  60.                 //初始化File  
  61.                 String path=Environment.getExternalStorageDirectory().toString()  
  62.                         +File.separator  
  63.                         +"genwoxue"  
  64.                         +File.separator  
  65.                         +FILENAME;  
  66.                 file=new File(path);  
  67.                   
  68.                 //如果當前文件的父文件夾不存在,則創建genwoxue文件夾  
  69.                 if(!file.getParentFile().exists())  
  70.                     file.getParentFile().mkdirs();  
  71.                       
  72.                 //實例化DocumentBuilderFactory  
  73.                 DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();  
  74.                 //獲取DocumentBuilder對象  
  75.                 try {  
  76.                     builder=factory.newDocumentBuilder();  
  77.                 } catch (ParserConfigurationException e) {  
  78.                     e.printStackTrace();  
  79.                 }  
  80.                 //獲取Document對象  
  81.                 doc=builder.newDocument();  
  82.                 //建立節點  
  83.                 Element books=doc.createElement("books");  
  84.                 Element book=doc.createElement("book");  
  85.                 Element bookname=doc.createElement("bookname");  
  86.                 Element author=doc.createElement("author");  
  87.                 Element publisher=doc.createElement("publisher");  
  88.                       
  89.                 //添加內容  
  90.                 bookname.appendChild(doc.createTextNode("跟我學Android"));  
  91.                 author.appendChild(doc.createTextNode("蔣老夫子"));  
  92.                 publisher.appendChild(doc.createTextNode("人民郵電出版社"));  
  93.                       
  94.                 //設置節點關系  
  95.                 book.appendChild(bookname);  
  96.                 book.appendChild(author);  
  97.                 book.appendChild(publisher);  
  98.                       
  99.                 books.appendChild(book);  
  100.                 doc.appendChild(books);  
  101.                       
  102.                 //輸出到文件  
  103.                 TransformerFactory transfactory=TransformerFactory.newInstance();  
  104.                   
  105.                 try {  
  106.                     trans=transfactory.newTransformer();  
  107.                 } catch (TransformerConfigurationException e) {  
  108.                     e.printStackTrace();  
  109.                 }  
  110.                       
  111.                 trans.setOutputProperty(OutputKeys.ENCODING,"UTF-8");  
  112.                 DOMSource source=new DOMSource(doc);  
  113.                 StreamResult result=new StreamResult(file);  
  114.                       
  115.                 try {  
  116.                     trans.transform(source, result);  
  117.                 } catch (TransformerException e) {  
  118.                     e.printStackTrace();  
  119.                 }  
  120.             }  
  121.         });  
  122.           
  123.         btnRead.setOnClickListener(new OnClickListener(){  
  124.             public void onClick(View v)  
  125.             {  
  126.                 DocumentBuilder builder=null;  
  127.                 Document doc=null;  
  128.                 StringBuffer info=null;  
  129.   
  130.                 //判斷外部存儲卡是否存在  
  131.                 if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){  
  132.                     Toast.makeText(getApplicationContext(), "讀取失敗,SD存儲卡不存在!", Toast.LENGTH_LONG).show();    
  133.                     return;  
  134.                 }  
  135.                   
  136.                 //初始化File  
  137.                 String path=Environment.getExternalStorageDirectory().toString()  
  138.                         +File.separator  
  139.                         +"genwoxue"  
  140.                         +File.separator  
  141.                         +FILENAME;  
  142.                 file=new File(path);  
  143.                   
  144.                 if(!file.exists()){  
  145.                     Toast.makeText(getApplicationContext(), "文件不存在!", Toast.LENGTH_LONG).show();    
  146.                     return;  
  147.                 }  
  148.                   
  149.                 //實例化DocumentBuilderFactory  
  150.                 DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();  
  151.                 //獲取DocumentBuilder對象  
  152.                 try {  
  153.                     builder=factory.newDocumentBuilder();  
  154.                 } catch (ParserConfigurationException e) {  
  155.                     e.printStackTrace();  
  156.                 }  
  157.                   
  158.                 //獲取Document對象  
  159.                 try {  
  160.                     doc=builder.parse(file);  
  161.                 } catch (SAXException e) {  
  162.                     e.printStackTrace();  
  163.                 } catch (IOException e) {  
  164.                     e.printStackTrace();  
  165.                 }  
  166.                       
  167.                 //查找book節點  
  168.                 NodeList nodelist=doc.getElementsByTagName("book");  
  169.                       
  170.                 //獲取節點文本內容  
  171.                 info=new StringBuffer();  
  172.                       
  173.                 for(int i=0;i<nodelist.getLength();i++){  
  174.                     Element element=(Element)nodelist.item(i);  
  175.                     info.append(info+element.getElementsByTagName("bookname").item(0).getFirstChild().getNodeValue()).append("☆☆☆");  
  176.                     info.append(element.getElementsByTagName("author").item(0).getFirstChild().getNodeValue()).append("☆☆☆");  
  177.                     info.append(element.getElementsByTagName("publisher").item(0).getFirstChild().getNodeValue()).append("☆☆☆");  
  178.                 }  
  179.                       
  180.                 Toast.makeText(getApplicationContext(), info.toString(), Toast.LENGTH_LONG).show();      
  181.             }  
  182.         });  
  183.     }  
  184. }  


三、配置文件

打開“AndroidManifest.xml”文件。

然後輸入以下代碼:

[html] view plain copy  
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.genwoxue.filedom"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.   
  7.     <uses-sdk  
  8.         android:minSdkVersion="8"  
  9.         android:targetSdkVersion="15" />  
  10.     <strong><span style="color:#ff0000;"><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>  
  11.     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  
  12. </span></strong>  
  13.     <application  
  14.         android:allowBackup="true"  
  15.         android:icon="@drawable/ic_launcher"  
  16.         android:label="@string/app_name"  
  17.         android:theme="@style/AppTheme" >  
  18.         <activity  
  19.             android:name="com.genwoxue.filedom.MainActivity"  
  20.             android:label="@string/app_name" >  
  21.             <intent-filter>  
  22.                 <action android:name="android.intent.action.MAIN" />  
  23.   
  24.                 <category android:name="android.intent.category.LAUNCHER" />  
  25.             </intent-filter>  
  26.         </activity>  
  27.     </application>  
  28.   
  29. </manifest>  

注意:由於要進行讀寫外部存儲卡操作,故而需要在AndroidManifest.xml文件中添加兩項權限:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

四、運行結果

\ \

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved