如何在Android中使用SAX解析器解析XML?


簡介

Android是一個開源的作業系統,它基於由Google開發的Linux核心。我們可以在Android應用程式中使用多種方法來解析資料,例如JSON解析、XML解析等等。對於XML檔案的解析,可以使用SAX解析器。在本文中,我們將瞭解如何在Android中使用SAX解析器解析XML。

實現

我們將建立一個簡單的應用程式,其中我們將建立一個TextView用於顯示應用程式的標題。之後,我們將建立另一個TextView,用於顯示使用SAX解析器從XML檔案解析的資料。現在讓我們轉到Android Studio,在Android Studio中建立一個新專案。

步驟1:在Android Studio中建立新專案

導航到Android Studio,如下面的螢幕截圖所示。在下面的螢幕截圖中,點選“新建專案”以建立一個新的Android Studio專案。

點選“新建專案”後,您將看到下面的螢幕。

在此螢幕中,我們只需選擇“空活動”並點選“下一步”。點選“下一步”後,您將看到下面的螢幕。

在此螢幕中,我們只需指定專案名稱。然後包名將自動生成。

注意:確保選擇Java作為語言。

指定所有詳細資訊後,點選“完成”以建立一個新的Android Studio專案。

專案建立完成後,我們將看到兩個開啟的檔案,即activity_main.xml和MainActivity.java檔案。

步驟2:使用activity_main.xml

導航到activity_main.xml。如果此檔案不可見,則要開啟此檔案,在左側窗格中導航到app>res>layout>activity_main.xml以開啟此檔案。開啟此檔案後,將以下程式碼新增到其中。程式碼中添加了註釋以詳細瞭解。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent">
   <!-- on below line creating the heading of our application -->
   <TextView
       android:id="@+id/idTVHeading"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_above="@id/idTVParser"
       android:layout_margin="10dp"
       android:layout_marginTop="90dp"
       android:padding="8dp"
       android:text="XML Parsing in Android using SAX Parser"
       android:textAlignment="center"
       android:textColor="@color/black"
       android:textSize="20sp"
       android:textStyle="bold" />
   <!-- on below line creating a list view for displaying the list of programming languages -->
   <TextView
       android:id="@+id/idTVParser"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_centerInParent="true"
       android:layout_margin="8dp"
       android:padding="4dp"
       android:textAlignment="center"
       android:textColor="@color/black"
       android:textSize="18sp" />
</RelativeLayout>

說明 - 在上面的程式碼中,我們建立了一個根佈局作為相對佈局。在此佈局內,我們建立了一個TextView,用於顯示應用程式的標題。之後,我們建立了另一個TextView,用於顯示從XML檔案解析的資料。

步驟3:建立XML檔案以儲存我們的資料

導航到app>java>您的應用程式包名>右鍵點選它>新建資料夾>Assets資料夾。現在將建立assets資料夾。現在,我們將在assets資料夾中建立一個XML檔案。要建立XML檔案,請導航到assets資料夾,右鍵點選它>新建Android資原始檔,並將其命名為file.xml。建立該檔案後,將以下程式碼新增到其中。程式碼中添加了註釋以詳細瞭解。

<?xml version="1.0" encoding="utf-8"?>
<records>
   <!-- on below line creating a language and inside that creating a name and description for it -->
   <language>
       <name>Java</name>
       <description>Java is a high-level, class-based, object-oriented programming language that is
           designed to have as few implementation dependencies as possible.
       </description>
   </language>
</records>

步驟4:使用MainActivity.java檔案

導航到MainActivity.java。如果此檔案不可見,則要開啟此檔案,在左側窗格中導航到app>res>layout>MainActivity.java以開啟此檔案。開啟此檔案後,將以下程式碼新增到其中。程式碼中添加了註釋以詳細瞭解。

package com.example.java_test_application;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.io.InputStream;
import java.util.ArrayList;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
public class MainActivity extends AppCompatActivity {
   // creating variable for text view on below line.
   private TextView parserTV;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       // initializing variables for text view on below line.
       parserTV = findViewById(R.id.idTVParser);
       try {
           // creating a variable for sax parser factory on below line.
           SAXParserFactory factory = SAXParserFactory.newInstance();
           // creating and initializing variable for sax parser on below line.
           SAXParser saxParser = factory.newSAXParser();
           // creating a variable for default handler and initializing it on below line.
           DefaultHandler handler = new DefaultHandler() {
               // creating a boolean for language name..
               boolean name = false;
               // creating a boolean variable for kanguage description.
               boolean description = false;

               // on below line creating a method to check start element.
               public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
                   // on below line checking if name is present in the xml and of present marking the name boolean variable as true.
                   if (qName.equalsIgnoreCase("name")) {
                       name = true;
                   }
                   // on below line checking if description for the language is present in the xml and then marking the description also as true.
                   if (qName.equalsIgnoreCase("description")) {
                       description = true;
                   }
               }

               // on below line creating an end element method.
               public void endElement(String uri, String localName, String qName) throws SAXException {
               }

               // on below line getting characters from the method.
               public void characters(char ch[], int start, int length) throws SAXException {
                   // on below line checking if name is true
                   if (name) {
                       // on below line setting name in our parse text view.
                       // changing the name to false.
                       parserTV.setText(parserTV.getText() + new String(ch, start, length) + "

"); name = false; } // on below line checking if description is true. if (description) { // on below line setting description in our parse text view. // changing the description to false. parserTV.setText("

" + parserTV.getText() + new String(ch, start, length)); description = false; } }//end of characters };//end of DefaultHandler object // on below line getting thr file using input stream. InputStream is = getAssets().open("file.xml"); // on below line parsing the file using sax parser saxParser.parse(is, handler); // on below line handling the exception. } catch (Exception e) { e.printStackTrace(); } } }

說明 - 在上面的程式碼中,首先我們為TextView建立變數。現在我們將看到onCreate方法。這是每個Android應用程式的預設方法。當應用程式檢視建立時,將呼叫此方法。在此方法內,我們設定內容檢視,即名為activity_main.xml的佈局檔案,以從該檔案設定UI。在onCreate方法內,我們使用我們在activity_main.xml檔案中給定的id初始化TextView變數。之後,我們在try-catch塊中建立並初始化SAX Parser Factory、SAX Parser和Default handler變數。

在此,我們建立了一個startElement方法和一個endElement方法。startElement方法將檢查我們正在搜尋的資料是否存在於XML中。然後,我們建立了一個characters方法,用於從XML檔案讀取資料並將該資料設定到我們的TextView中。之後,我們建立了一個InputStream並傳遞我們要載入資料的檔名。在我們的例子中,我們傳遞檔名file.xml。然後,我們呼叫sax解析器的parse方法來解析資料。最後,我們添加了一個catch塊用於異常處理。

新增上述程式碼後,我們只需點選頂部欄中的綠色圖示即可在移動裝置上執行我們的應用程式。

注意:確保已連線到您的真實裝置或模擬器。

輸出

結論

在本文中,我們瞭解瞭如何在Android中使用SAX解析器解析XML。

更新於: 2023年5月9日

398 次瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告