Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách dùng XMLPullParser để parse XML trong Android bằng Kotlin

Giới thiệu

Bài viết này hướng dẫn cách sử dụng XMLPullParser để phân tích cú pháp (parse) file XML trong Android sử dụng Kotlin.

Các bước thực hiện

Bước 1: Tạo dự án mới

Mở Android Studio, chọn File → New Project và điền đầy đủ thông tin để tạo dự án mới.

Bước 2: Thiết kế giao diện chính (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://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>

Bước 3: Tạo layout item (res/layout/row.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://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>

Bước 4: Tạo file XML data (assets/model.xml)

Tạo thư mục assets (chuột phải module → New → Folder → Assets Folder), sau đó tạo file model.xml:

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

Bước 5: Viết logic xử lý (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()
        }
    }
}

Bước 6: Cấu hình Manifest (androidManifest.xml)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://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>

Chạy ứng dụng

Kết nối thiết bị Android thực với máy tính. Trong Android Studio, mở file activity và nhấn biểu tượng Run trên thanh công cụ. Chọn thiết bị di động của bạn và kiểm tra màn hình hiển thị.

Giải thích: XMLPullParser là parser kiểu pull (kéo), hiệu quả bộ nhớ. Duyệt qua START_TAG, TEXT, END_TAG. SimpleAdapter map dữ liệu HashMap vào layout row.xml.