使用SAX Parser的Kotlin Android XML解析

XML文档通常用于在Internet上共享数据。 XML格式提供的数据能够经常更新, 并且解析它们是基于网络的应用程序的常见任务。
在Android中, 有三种类型的XML解析器可以解析XML数据并在android应用程序中读取它们, 它们是:

  1. DOM解析器
  2. SAX解析器
  3. XMLPullParser
在Android中, SAX(XML的简单API)被广泛用于XML解析的API。 SAX解析器将逐字符检查XML文档, 并将其转换为一系列事件, 例如startElement(), endElement()和character()。要使用SAX解析器读取和解析XML数据, 我们需要在android应用程序中创建SAXParserFactory, SAXParser和DefaultHandler对象的实例。
使用SAX Parser进行XML解析的示例 在此示例中, 我们将使用SAX解析器解析XML数据并将其显示在ListView中。
activity_main.xml
在activity_main.xml布局中添加ListView。
< ?xml version="1.0" encoding="utf-8"?> < android.support.constraint.ConstraintLayout 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"tools:context="example.srcmini.com.kotlinxmlparsingusingsaxparser.MainActivity"> < ListViewandroid:id="@+id/listView"android:layout_width="match_parent"android:layout_height="match_parent"> < /ListView> < /android.support.constraint.ConstraintLayout>

empdetail.xml
在资产目录中创建XML文档empdetail.xml, 以使用SAX解析器解析数据。
< ?xml version="1.0" encoding="utf-8"?> < records> < employee> < name> Sachin Kumar< /name> < salary> 50000< /salary> < designation> Developer< /designation> < /employee> < employee> < name> Rahul Kumar< /name> < salary> 60000< /salary> < designation> Team Leader< /designation> < /employee> < employee> < name> John Mike< /name> < salary> 70000< /salary> < designation> Manager< /designation> < /employee> < employee> < name> Ajay Kumar< /name> < salary> 45000< /salary> < designation> Developer< /designation> < /employee> < employee> < name> Toni Nayer< /name> < salary> 55000< /salary> < designation> Marketing< /designation> < /employee> < employee> < name> Mr Bony< /name> < salary> 42000< /salary> < designation> Sales< /designation> < /employee> < employee> < name> Raj Kumar< /name> < salary> 30000< /salary> < designation> Production< /designation> < /employee> < employee> < name> Rahul Kumar< /name> < salary> 60000< /salary> < designation> Team Leader< /designation> < /employee> < employee> < name> John Mike< /name> < salary> 70000< /salary> < designation> Manager< /designation> < /employee> < employee> < name> Sachin Kumar< /name> < salary> 50000< /salary> < designation> Developer< /designation> < /employee> < employee> < name> Rahul Kumar< /name> < salary> 60000< /salary> < designation> Team Leader< /designation> < /employee> < employee> < name> John Mike< /name> < salary> 70000< /salary> < designation> Manager< /designation> < /employee> < /records>

custom_list.xml
创建一个自定义布局以将数据列表显示到ListView中。
< ?xml version="1.0" encoding="utf-8"?> < LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="horizontal"> < LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:layout_weight="1"android:orientation="vertical"> < TextViewandroid:id="@+id/name"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="name"android:textStyle="bold"android:layout_marginLeft="15dp"android:layout_marginStart="15dp"android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" /> < TextViewandroid:id="@+id/salary"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="salary"android:layout_marginLeft="15dp"android:layout_marginStart="15dp"android:layout_marginTop="5dp"android:textSize="16sp"/> < TextViewandroid:id="@+id/designation"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="designation"android:layout_marginLeft="15dp"android:layout_marginStart="15dp"android:layout_marginTop="5dp"android:textSize="16sp"/> < /LinearLayout> < /LinearLayout>

MainActivity.kt
添加以下代码, 以使用SAX解析器读取和解析XML数据。创建SAXParserFactory, SAXParser和DefaultHandler对象的实例。
HashMap < String, String> 用于从XML文档读取数据并将其添加到ArrayList()中。
package example.srcmini.com.kotlinxmlparsingusingsaxparserimport android.support.v7.app.AppCompatActivityimport android.os.Bundleimport org.xml.sax.helpers.DefaultHandlerimport javax.xml.parsers.SAXParserFactoryimport android.widget.ListViewimport android.widget.SimpleAdapterimport org.xml.sax.SAXExceptionimport java.io.IOExceptionimport java.util.ArrayListimport java.util.HashMapimport javax.xml.parsers.ParserConfigurationExceptionimport javax.xml.parsers.SAXParserclass MainActivity : AppCompatActivity() {internal var empList = ArrayList< HashMap< String, String> > ()internal var empData = http://www.srcmini.com/HashMap< String, String> ()override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)val lv:ListView = findViewById(R.id.listView)try {//instancing the SAXParserFactory classval parserFactory:SAXParserFactory = SAXParserFactory.newInstance()//instancing the SAXParser classval saxParser:SAXParser = parserFactory.newSAXParser()val defaultHandler= object : DefaultHandler() {var currentValue =""var currentElement = false//overriding the startElement() method of DefaultHandleroverride fun startElement(uri: String, localName: String, qName: String, attributes: org.xml.sax.Attributes) {currentElement = truecurrentValuehttp://www.srcmini.com/= ""if (localName == "employee") {empData = http://www.srcmini.com/HashMap()}}//overriding the endElement() method of DefaultHandleroverride fun endElement(uri: String, localName: String, qName: String) {currentElement = falseif (localName.equals("name", ignoreCase = true))empData["name"] = currentValueelse if (localName.equals("salary", ignoreCase = true))empData["salary"] = currentValueelse if (localName.equals("designation", ignoreCase = true))empData["designation"] = currentValueelse if (localName.equals("employee", ignoreCase = true))empList.add(empData)}//overriding the characters() method of DefaultHandleroverride fun characters(ch: CharArray, start: Int, length: Int) {if (currentElement) {currentValue = http://www.srcmini.com/currentValue + String(ch, start, length)}}}val istream = assets.open("empdetail.xml")saxParser.parse(istream, defaultHandler)//creating Adapter class to access the custom listval adapter = SimpleAdapter(this@MainActivity, empList, R.layout.custom_list, arrayOf("name", "salary", "designation"), intArrayOf(R.id.name, R.id.salary, R.id.designation))lv.adapter = adapter} catch (e: IOException) {e.printStackTrace()} catch (e: ParserConfigurationException) {e.printStackTrace()} catch (e: SAXException) {e.printStackTrace()}}}

【使用SAX Parser的Kotlin Android XML解析】输出:
使用SAX Parser的Kotlin Android XML解析

文章图片

    推荐阅读