如何在Android中使用Kotlin和XMLPullParser解析XML?


此示例演示瞭如何使用Kotlin在Android中使用XMLPullParser解析XML。

步驟1 − 在Android Studio中建立一個新專案,轉到檔案 ⇒ 新建專案,並填寫所有必需的詳細資訊以建立新專案。

步驟2 − 將以下程式碼新增到res/layout/activity_main.xml。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical">
   <ListView
      android:id="@+id/listView"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:dividerHeight="1dp" />
</LinearLayout>

步驟3 − 建立一個佈局資原始檔(row.xml)並新增以下程式碼 −

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:padding="4dp">
   <TextView
      android:id="@+id/tvName"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:textColor="@android:color/background_dark"
      android:textSize="16sp"
      android:textStyle="bold" />
   <TextView
      android:id="@+id/tvDesignation"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_below="@id/tvName"
      android:layout_marginTop="7dp"
      android:textColor="#343434"
      android:textSize="12sp" />
   <TextView
      android:id="@+id/tvLocation"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignBaseline="@+id/tvDesignation"
      android:layout_alignBottom="@+id/tvDesignation"
      android:layout_alignParentEnd="true"
      android:textColor="@android:color/background_dark"
      android:textSize="16sp" />
</RelativeLayout>

步驟5 − 建立一個新的asset資料夾,並在asset資料夾內建立一個Android資原始檔(model.xml)並新增以下程式碼 −

<?xml version="1.0" encoding="utf-8"?>
<resources>
<users>
   <user>
      <name>Sehwag</name>
      <designation>Vice Captain</designation>
      <loation>Delhi</loation>
   </user>
   <user>
      <name>Ashwin</name>
      <designation>Off Spin Bowler</designation>
      <loation>Chennai</loation>
   </user>
   <user>
      <name>Dhoni</name>
      <designation>Captain</designation>
      <loation>Ranchi</loation>
   </user>
</users>
</resources>

步驟6 − 將以下程式碼新增到src/MainActivity.kt

import android.os.Bundle
import android.widget.ListAdapter
import android.widget.ListView
import android.widget.SimpleAdapter
import androidx.appcompat.app.AppCompatActivity
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserException
import org.xmlpull.v1.XmlPullParserFactory
import java.io.IOException
class MainActivity : AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      try {
         val userList = ArrayList<java.util.HashMap<String?, String?>>()
         var user: HashMap<String?, String?>? = HashMap()
         val lv: ListView = findViewById(R.id.listView)
         val inputStream = assets.open("model.xml")
         val parserFactory: XmlPullParserFactory = XmlPullParserFactory.newInstance()
         val parser: XmlPullParser = parserFactory.newPullParser()
         parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true)
         parser.setInput(inputStream, null)
         var tag: String?
         var text = ""
         var event = parser.eventType
         while (event != XmlPullParser.END_DOCUMENT) {
            tag = parser.name
            when (event) {
               XmlPullParser.START_TAG -> if (tag == "user") user = HashMap()
               XmlPullParser.TEXT −> text = parser.text
               XmlPullParser.END_TAG −> when (tag) {
                  "name" −> user!!["name"] = text
                  "designation" −> user!!["designation"] = text
                  "location" −> user!!["location"] = text
                  "user" −> if (user != null) userList.add(user)
               }
            }
            event = parser.next()
         }
         val adapter: ListAdapter = SimpleAdapter(this@MainActivity, userList, R.layout.row,
         arrayOf("name", "designation", "location"), intArrayOf(R.id.tvName,
         R.id.tvDesignation, R.id.tvLocation))
         lv.adapter = adapter
      } catch (e: IOException) {
         e.printStackTrace()
      } catch (e: XmlPullParserException) {
         e.printStackTrace()
      }
   }
}

步驟6 − 將以下程式碼新增到androidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

讓我們嘗試執行您的應用程式。我假設您已將您的實際Android移動裝置連線到您的計算機。要從Android Studio執行應用程式,請開啟您專案中的一個活動檔案,然後單擊工具欄中的執行圖示 。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕。

更新於:2020年11月5日

952 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.