XML Parsing - How to parse XML data using DOM in Android Studio using Kotlin.

Last updated Dec 18, 2021

In this article, we will see how to parse xml data using DOM (Document Object Model) parser in Android Studio by using Kotlin Language. XML document is commonly used to share the data on the internet. The data provided in XML format are able to update frequently and parsing them is a common task for network-based apps.

Implementation:

Step 1:  Create a new Project in android studio.

Go to File > New > New Project > Empty Activity > Next > Enter Name > Select Language Kotlin > Finish

 

Step 2: Go to activity_main.xml file and add the following code

   

<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </ListView>

</LinearLayout>


   

 

 

Step 3: Create a new Assets folder

app > right-click > new > Folder > Assets Folder > Finish.

 

Step 4: Create a new xml resource file name custom_layout.

app > assets > right-click > new > Android Resource File > enter name > change resource type to XML > OK.

(Sometimes file goes into res > xml > file, cut the file and paste inside assets folder).

 

Step 5: Open personData.xml fileand add following data

<?xml version="1.0" encoding="utf-8"?>
<records>
    <person>
        <name>Sachin Kumar</name>
        <age>23</age>
    </person>
    <person>
        <name>Mohit John</name>
        <age>25</age>
    </person>
    <person>
        <name>Arun Singh</name>
        <age>28</age>
    </person>
    <person>
        <name>Kartik Jin</name>
        <age>21</age>
    </person>
    <person>
        <name>Manish Jain</name>
        <age>22</age>
    </person>
    <person>
        <name>Lokesh Mehta</name>
        <age>29</age>
    </person>
    <person>
        <name>Virk Kumar</name>
        <age>31</age>
    </person>
    <person>
        <name>Fateh Kol</name>
        <age>42</age>
    </person>
</records>

 

 

Step 6: After it, create a new layout resource file by follow this

app > res > layout > right-click > new > Layout Resource File > enter name (custom_layout) > OK.

 

Step 7: Open custom_layout.xml file and add the following code

<?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">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="vertical">

        <TextView
            android: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" />

        <TextView
            android:id="@+id/age"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="age"
            android:layout_marginLeft="15dp"
            android:layout_marginStart="15dp"
            android:layout_marginTop="5dp"
            android:textSize="16sp"/>


Step 8:  Open MainActivity.kt file and add the following code.

var empDataHashMap = HashMap()
    var empList: ArrayList> = ArrayList()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        try {
            val lv = findViewById(R.id.listView)
            val istream = assets.open("personData.xml")
            val builderFactory = DocumentBuilderFactory.newInstance()
            val docBuilder = builderFactory.newDocumentBuilder()
            val doc = docBuilder.parse(istream)
            //reading the tag "employee" of empdetail file
            val nList = doc.getElementsByTagName("person")
            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 value
                    empDataHashMap = HashMap()
                    val element = nList.item(i) as Element
                    empDataHashMap.put("name", getNodeValue("name", element))
                    empDataHashMap.put("age", getNodeValue("age", element))
                    //adding the HashMap data to ArrayList
                    empList.add(empDataHashMap)
                }
            }
            val adapter = SimpleAdapter(this@MainActivity, empList, R.layout.custom_layout, arrayOf("name", "age"), intArrayOf(R.id.name, R.id.age))
            lv.setAdapter(adapter)
        } catch (e: IOException) {
            e.printStackTrace()
        } catch (e: ParserConfigurationException) {
            e.printStackTrace()
        } catch (e: SAXException) {
            e.printStackTrace()
        }

    }
    // function to return node value
    protected 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 ""
    }

 

Step 9: Run the app on emulator or real device, you will get the output as given below

OUTPUT:
 

XML Parsing Example


 

Complete Source Code of XML Parsing using DOM Example 

activity_main.xml file

<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </ListView>

</LinearLayout>

 

 

MainActivity.kt file

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ListView
import android.widget.SimpleAdapter
import org.w3c.dom.Element
import org.w3c.dom.Node
import org.xml.sax.SAXException
import java.io.IOException
import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.parsers.ParserConfigurationException

class MainActivity : AppCompatActivity() {
    var empDataHashMap = HashMap()
    var empList: ArrayList> = ArrayList()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        try {
            val lv = findViewById(R.id.listView)
            val istream = assets.open("personData.xml")
            val builderFactory = DocumentBuilderFactory.newInstance()
            val docBuilder = builderFactory.newDocumentBuilder()
            val doc = docBuilder.parse(istream)
            //reading the tag "employee" of empdetail file
            val nList = doc.getElementsByTagName("person")
            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 value
                    empDataHashMap = HashMap()
                    val element = nList.item(i) as Element
                    empDataHashMap.put("name", getNodeValue("name", element))
                    empDataHashMap.put("age", getNodeValue("age", element))
                    //adding the HashMap data to ArrayList
                    empList.add(empDataHashMap)
                }
            }
            val adapter = SimpleAdapter(this@MainActivity, empList, R.layout.custom_layout, arrayOf("name", "age"), intArrayOf(R.id.name, R.id.age))
            lv.setAdapter(adapter)
        } catch (e: IOException) {
            e.printStackTrace()
        } catch (e: ParserConfigurationException) {
            e.printStackTrace()
        } catch (e: SAXException) {
            e.printStackTrace()
        }

    }
    // function to return node value
    protected 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 ""
    }
}

 

custom_layout.xml file

<?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">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="vertical">

        <TextView
            android: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" />

        <TextView
            android:id="@+id/age"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="age"
            android:layout_marginLeft="15dp"
            android:layout_marginStart="15dp"
            android:layout_marginTop="5dp"
            android:textSize="16sp"/>
    </LinearLayout>
</LinearLayout>

 

personData.xml file

<?xml version="1.0" encoding="utf-8"?>
<records>
    <person>
        <name>Sachin Kumar</name>
        <age>23</age>
    </person>
    <person>
        <name>Mohit John</name>
        <age>25</age>
    </person>
    <person>
        <name>Arun Singh</name>
        <age>28</age>
    </person>
    <person>
        <name>Kartik Jin</name>
        <age>21</age>
    </person>
    <person>
        <name>Manish Jain</name>
        <age>22</age>
    </person>
    <person>
        <name>Lokesh Mehta</name>
        <age>29</age>
    </person>
    <person>
        <name>Virk Kumar</name>
        <age>31</age>
    </person>
    <person>
        <name>Fateh Kol</name>
        <age>42</age>
    </person>
</records>

 

Conclusion: In this article we have covered how to parse XML Document Data using DOM Parser in Android Studio by using Kotlin Language.
 

<?xml version="1.0" encoding="utf-8"?>
<records>
    <person>
        <name>Sachin Kumar</name>
        <age>23</age>
    </person>
    <person>
        <name>Mohit John</name>
        <age>25</age>
    </person>
    <person>
        <name>Arun Singh</name>
        <age>28</age>
    </person>
    <person>
        <name>Kartik Jin</name>
        <age>21</age>
    </person>
    <person>
        <name>Manish Jain</name>
        <age>22</age>
    </person>
    <person>
        <name>Lokesh Mehta</name>
        <age>29</age>
    </person>
    <person>
        <name>Virk Kumar</name>
        <age>31</age>
    </person>
    <person>
        <name>Fateh Kol</name>
        <age>42</age>
    </person>
</records>

 

 

Step 6: After it, create a new layout resource file by follow this

app > res > layout > right-click > new > Layout Resource File > enter name (custom_layout) > OK.

 

Step 7: Open custom_layout.xml file and add the following code

<?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">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="vertical">

        <TextView
            android: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" />

        <TextView
            android:id="@+id/age"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="age"
            android:layout_marginLeft="15dp"
            android:layout_marginStart="15dp"
            android:layout_marginTop="5dp"
            android:textSize="16sp"/>


Step 8:  Open MainActivity.kt file and add the following code.

var empDataHashMap = HashMap()
    var empList: ArrayList> = ArrayList()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        try {
            val lv = findViewById(R.id.listView)
            val istream = assets.open("personData.xml")
            val builderFactory = DocumentBuilderFactory.newInstance()
            val docBuilder = builderFactory.newDocumentBuilder()
            val doc = docBuilder.parse(istream)
            //reading the tag "employee" of empdetail file
            val nList = doc.getElementsByTagName("person")
            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 value
                    empDataHashMap = HashMap()
                    val element = nList.item(i) as Element
                    empDataHashMap.put("name", getNodeValue("name", element))
                    empDataHashMap.put("age", getNodeValue("age", element))
                    //adding the HashMap data to ArrayList
                    empList.add(empDataHashMap)
                }
            }
            val adapter = SimpleAdapter(this@MainActivity, empList, R.layout.custom_layout, arrayOf("name", "age"), intArrayOf(R.id.name, R.id.age))
            lv.setAdapter(adapter)
        } catch (e: IOException) {
            e.printStackTrace()
        } catch (e: ParserConfigurationException) {
            e.printStackTrace()
        } catch (e: SAXException) {
            e.printStackTrace()
        }

    }
    // function to return node value
    protected 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 ""
    }

 

Step 9: Run the app on emulator or real device, you will get the output as given below

OUTPUT:
 

XML Parsing Example


 

Complete Source Code of XML Parsing using DOM Example 

activity_main.xml file

<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </ListView>

</LinearLayout>

 

 

MainActivity.kt file

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ListView
import android.widget.SimpleAdapter
import org.w3c.dom.Element
import org.w3c.dom.Node
import org.xml.sax.SAXException
import java.io.IOException
import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.parsers.ParserConfigurationException

class MainActivity : AppCompatActivity() {
    var empDataHashMap = HashMap()
    var empList: ArrayList> = ArrayList()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        try {
            val lv = findViewById(R.id.listView)
            val istream = assets.open("personData.xml")
            val builderFactory = DocumentBuilderFactory.newInstance()
            val docBuilder = builderFactory.newDocumentBuilder()
            val doc = docBuilder.parse(istream)
            //reading the tag "employee" of empdetail file
            val nList = doc.getElementsByTagName("person")
            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 value
                    empDataHashMap = HashMap()
                    val element = nList.item(i) as Element
                    empDataHashMap.put("name", getNodeValue("name", element))
                    empDataHashMap.put("age", getNodeValue("age", element))
                    //adding the HashMap data to ArrayList
                    empList.add(empDataHashMap)
                }
            }
            val adapter = SimpleAdapter(this@MainActivity, empList, R.layout.custom_layout, arrayOf("name", "age"), intArrayOf(R.id.name, R.id.age))
            lv.setAdapter(adapter)
        } catch (e: IOException) {
            e.printStackTrace()
        } catch (e: ParserConfigurationException) {
            e.printStackTrace()
        } catch (e: SAXException) {
            e.printStackTrace()
        }

    }
    // function to return node value
    protected 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 ""
    }
}

 

custom_layout.xml file

<?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">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="vertical">

        <TextView
            android: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" />

        <TextView
            android:id="@+id/age"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="age"
            android:layout_marginLeft="15dp"
            android:layout_marginStart="15dp"
            android:layout_marginTop="5dp"
            android:textSize="16sp"/>
    </LinearLayout>
</LinearLayout>

 

personData.xml file

<?xml version="1.0" encoding="utf-8"?>
<records>
    <person>
        <name>Sachin Kumar</name>
        <age>23</age>
    </person>
    <person>
        <name>Mohit John</name>
        <age>25</age>
    </person>
    <person>
        <name>Arun Singh</name>
        <age>28</age>
    </person>
    <person>
        <name>Kartik Jin</name>
        <age>21</age>
    </person>
    <person>
        <name>Manish Jain</name>
        <age>22</age>
    </person>
    <person>
        <name>Lokesh Mehta</name>
        <age>29</age>
    </person>
    <person>
        <name>Virk Kumar</name>
        <age>31</age>
    </person>
    <person>
        <name>Fateh Kol</name>
        <age>42</age>
    </person>
</records>

 

Conclusion: In this article we have covered how to parse XML Document Data using DOM Parser in Android Studio by using Kotlin Language.
 

-->
Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

651 Views