使用DOM解析器的Kotlin Android XML解析

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

  1. DOM解析器
  2. SAX解析器
  3. XMLPullParser
Android DOM(文档对象模型)解析器使用基于对象的方法来创建和解析android应用程序中的XML文件。 DOM解析器将XML文件加载到内存中以解析XML文档。由于这个原因, 它消耗更多的内存。
使用DOM解析器进行XML解析的示例 在此示例中, 我们解析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.kotlinxmlparsingusingdomparser.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, 以使用DOM解析器解析数据。
< ?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
添加以下代码以使用DOM解析器读取和解析XML数据。创建DocumentBuilderFactory, DocumentBuilder和Document对象的实例。
HashMap < String, String> 用于从XML文档读取数据并将其添加到ArrayList()中。
package example.srcmini.com.kotlinxmlparsingusingdomparserimport android.support.v7.app.AppCompatActivityimport android.os.Bundleimport android.widget.ListViewimport android.widget.SimpleAdapterimport org.w3c.dom.Elementimport org.w3c.dom.Nodeimport org.xml.sax.SAXExceptionimport java.io.IOExceptionimport javax.xml.parsers.DocumentBuilderFactoryimport javax.xml.parsers.ParserConfigurationExceptionclass MainActivity : AppCompatActivity() {var empDataHashMap = HashMap< String, String> ()var empList: ArrayList< HashMap< String, String> > = ArrayList()override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)try {val lv = findViewById< ListView> (R.id.listView)val istream = assets.open("empdetail.xml")val builderFactory = DocumentBuilderFactory.newInstance()val docBuilder = builderFactory.newDocumentBuilder()val doc = docBuilder.parse(istream)//reading the tag "employee" of empdetail fileval nList = doc.getElementsByTagName("employee")for (i in 0 until nList.getLength()) {if (nList.item(0).getNodeType().equals(Node.ELEMENT_NODE) ) {//creating instance of HashMap to put the data of node valueempDataHashMap = HashMap()val element = nList.item(i) as ElementempDataHashMap.put("name", getNodeValue("name", element))empDataHashMap.put("salary", getNodeValue("salary", element))empDataHashMap.put("designation", getNodeValue("designation", element))//adding the HashMap data to ArrayListempList.add(empDataHashMap)}}val adapter = SimpleAdapter(this@MainActivity, empList, R.layout.custom_list, arrayOf("name", "salary", "designation"), intArrayOf(R.id.name, R.id.salary, R.id.designation))lv.setAdapter(adapter)} catch (e: IOException) {e.printStackTrace()} catch (e: ParserConfigurationException) {e.printStackTrace()} catch (e: SAXException) {e.printStackTrace()}}// function to return node valueprotected fun getNodeValue(tag: String, element: Element): String {val nodeList = element.getElementsByTagName(tag)val node = nodeList.item(0)if (node != null) {if (node.hasChildNodes()) {val child = node.getFirstChild()while (child != null) {if (child.getNodeType() === Node.TEXT_NODE) {return child.getNodeValue()}}}}return ""}}

【使用DOM解析器的Kotlin Android XML解析】输出:
使用DOM解析器的Kotlin Android XML解析

文章图片

    推荐阅读