XML Parsing in Android using DOM Parser
Last Updated :
23 Feb, 2021
Android DOM(Document Object Model) parser is a program that parses an XML document and extracts the required information from it. This parser uses an object-based approach for creating and parsing the XML files. In General, a DOM parser loads the XML file into the Android memory to parse the XML document. This results in more consumption of memory. The document is parsed through every possible node in the XML file. The XML file that contains the information to be extracted includes the following four main components:
- Prolog: The XML file will start with a prolog. Prolog contains the information about a file, which is available in the first line.
- Events: Events such as document start and end, tag start and end, etc. are contained in the XML file
- Text: It is a simple text present in between the opening and closing XML tag elements.
- Attributes: They are the additional properties of a tag present within the label.
Note that we are going to implement this project using the Kotlin language. One may also perform XML Parsing in another two ways. Please refer to the below articles:
What we are going to do?
- We need to have an XML file with some information so that we would make one. Place this file under the assets folder. This file is called and would be parsed.
- We want to show this data in the form of a list to implement a list view.
- In the Main program, we called the information file (under the assets folder) from the assets folder, and this is provided as an input stream.
- Using a DocumentBuilderFactory, we would create a new instance.
- Using a DocumentBuilder, we generate a new document builder.
- Using a Document method, we parse the input stream.
- As the information is in the form of nodes, we would create a NodeList and iterate through every node using a FOR loop.
- Specific information would be extracted in this loop and added to a list (declared earlier in the code).
- Using a ListAdapter, the data is broadcasted into the list view layout file.
Approach
To parse an XML file using a DOM parser in Android, we follow the following steps:
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Create an assets folder
Create an assets folder under the main folder in the Project Layout. Create an Android Resource File in this folder, where we shall put the information in the form of XML. Name this file as information.xml. For doing so refer to the following steps:
Click on Project as shown on the left side of the below image.
Expand until you find the main folder, right-click on it, go to New > Folder > Assets Folder
Then just click on the Finish button.
Now the asset folder is created successfully. Right-Click on the Assets Folder > New > Android Resource FIle
Give it name Information, change type to XML, and finish.
Note: Sometimes, right-clicking on the Assets folder and creating an Android Resource File creates a file in the res folder. If this happens, cut our file and paste it directly into the assets folder. This happens due to some internal settings.
Paste this information which is in the form of XML, that is to be displayed in the information.xml file. Below is the code for the information.xml file.
XML
<?xml version="1.0" encoding="utf-8"?>
<users>
<user>
<name>Steve</name>
<designation>Apple</designation>
</user>
<user>
<name>Sundar</name>
<designation>Google</designation>
</user>
<user>
<name>Jeff</name>
<designation>Amazon</designation>
</user>
</users>
Step 3: Working with the activity_main.xml file
Now go to the activity_main.xml file which represents the UI of the application. Create a ListView as shown. Below is the code for the activity_main.xml file.
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 to display the list-->
<ListView
android:id="@+id/user_list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:dividerHeight="1dp" />
</LinearLayout>
Step 4: Create another layout file
Go to app > res > layout > right-click > New > Layout Resource File and name the file as list. list.xml file is used to show the data in the ListView. Below is the code for the list.xml file.
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dip">
<!--textView to show the name node-->
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="17dp"
android:textStyle="bold" />
<!--textView to show the designation node-->
<TextView
android:id="@+id/designation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/name"
android:layout_marginTop="7dp"
android:textColor="#343434"
android:textSize="14dp" />
</RelativeLayout>
Step 5: Working with the MainActivity.kt file
Finally, go to the MainActivity.kt file, and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import android.os.Bundle
import android.widget.ListAdapter
import android.widget.ListView
import android.widget.SimpleAdapter
import androidx.appcompat.app.AppCompatActivity
import org.w3c.dom.Document
import org.w3c.dom.Element
import org.w3c.dom.Node
import org.w3c.dom.NodeList
import org.xml.sax.SAXException
import java.io.IOException
import java.io.InputStream
import javax.xml.parsers.DocumentBuilder
import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.parsers.ParserConfigurationException
open class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Try and Catch for avoiding the application to crash
try {
// This list will contain the data from the information.xml file
val userList: ArrayList<HashMap<String, String?>> = ArrayList()
// This listView will display the data from the information.xml file
val lv = findViewById<ListView>(R.id.user_list)
// The information.xml file will be taken in the form of input stream
val istream: InputStream = assets.open("information.xml")
// Steps to convert this input stream into a list
val builderFactory: DocumentBuilderFactory = DocumentBuilderFactory.newInstance()
val docBuilder: DocumentBuilder = builderFactory.newDocumentBuilder()
val doc: Document = docBuilder.parse(istream)
val nList: NodeList = doc.getElementsByTagName("user")
// Iterating through this list
for (i in 0 until nList.length) {
if (nList.item(0).nodeType === Node.ELEMENT_NODE) {
val user: HashMap<String, String?> = HashMap()
val elm: Element = nList.item(i) as Element
user["name"] = getNodeValue("name", elm)
user["designation"] = getNodeValue("designation", elm)
userList.add(user)
}
}
// Using Adapter to broadcast the information extracted
val adapter: ListAdapter = SimpleAdapter(
this,
userList,
R.layout.list,
arrayOf("name", "designation"),
intArrayOf(R.id.name, R.id.designation)
)
lv.adapter = adapter
} catch (e: IOException) {
e.printStackTrace()
} catch (e: ParserConfigurationException) {
e.printStackTrace()
} catch (e: SAXException) {
e.printStackTrace()
}
}
// A function to get the node value while parsing
private 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.firstChild
while (child != null) {
if (child.nodeType == Node.TEXT_NODE) {
return child.nodeValue
}
}
}
}
// Returns nothing if nothing was found
return ""
}
}
Output: Run on Emulator
Similar Reads
XML Parsing in Android using SAX Parser Generally, XML (Extensible Mark-up Language) is a commonly used data exchange format to interchange servers' data. In Android, SAX stands for Simple API for XML and is a widely used API for XML parsing. Like the DOM parser, the SAX parser is also used to perform in-memory operations to parse the XML
6 min read
XML Parsing in Android using XmlPullParser In android, the XMLPullParser interface provides the functionality to parse the XML files in android applications. The XMLPullParser is a simple and efficient parser method to parse the XML data when compared to other parser methods such as DOM Parser and SAX Parser. The XMLPullParser has a method n
5 min read
JSON Parsing in Android JSON (JavaScript Object Notation) is a straightforward data exchange format to interchange the server's data, and it is a better alternative for XML. This is because JSON is a lightweight and structured language. Android supports all the JSON classes such as JSONStringer, JSONObject, JSONArray, and
4 min read
What is Uri.parse() in Android? Uri stands for Uniform Resource Identifier. Uri is the sequence of the characters used to identify resources uniquely over the internet. In this article, we are going to see what is Uri.parse() method in Android. Step-by-Step Implementation Step 1: Create a New Project in Android Studio To create a
2 min read
A Complete Guide to Learn XML For Android App Development XML stands for Extensible Markup Language. XML is a markup language much like HTML used to describe data. It is derived from Standard Generalized Markup Language(SGML). Basically, the XML tags are not predefined in XML. We need to implement and define the tags in XML. XML tags define the data and us
7 min read
Implementation of HtmlTextView in Android HtmlTextView is an extended TextView component for Android, which can load HTML components by converting them into Android Spannables for viewing. In addition to HTML tags, the library allows to load images from the local drawable folder or from the Internet and also URL from the internet. In this a
2 min read
JAVA DOM Parser IntroductionJava is one of the most popular programming languages that is applicable to different purposes, starting from the web environment and ending with business-related ones. XML processing is one of the most important facets in the competence of Java as a language. The principal data exchange
8 min read
How to parse HTML DOM with DOMDocument ? What is DOM Parser? DOM Parser is a JavaScript library that parses HTML or XML documents into their corresponding Document Object Model (DOM). HTML is a markup language that describes the structure of web pages. The DOM is a tree representation of the document. In order to create a page, you need to
3 min read
Java Program to Extract Content From a XML Document An XML file contains data between the tags so it is complex to read the data when compared to other file formats like docx and txt. There are two types of parsers which parse an XML file: Object-Based (e.g. D.O.M)Event-Based (e.g. SAX, StAX) In this article, we will discuss how to parse XML using Ja
7 min read
How to Parse Invalid (Bad /Not Well-Formed) XML? Parsing invalid or not well-formed XML can be a necessity when dealing with data from diverse sources. While standard XML parsers expect well-formed XML, there are strategies and techniques to handle and extract information from malformed XML documents. In this article, we will explore how to parse
2 min read