Home » Android

How to parse XML file in Android?

In this article, we are going to learn about the XML parser and how we can parse an xml file in Android.
Submitted by Manu Jemini, on February 17, 2018

In the example below we are going to use the java.io.InputStream class to save the text in a file and Toast class to make a text on the screen that the text has been saved.

To implement this in your program you will need to import: java.io.InputStream, javax.xml.parsers.DocumentBuilder, javax.xml.parsers.DocumentBuilderFactory in your java file.

Then create a layout file with a single TextView like this:

<TextView
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	android:text="New Text"
	android:id="@+id/textView"
	android:layout_alignParentTop="true"
	android:layout_alignParentStart="true"
	android:layout_alignParentBottom="true"
	android:layout_alignParentEnd="true" />

We also need to create a XML file which we will parse.

<?xml version="1.0"?>
    <records>
    <students>
        <name>Manu Jemini</name>
        <course>B.E.</course>
        <semester>6</semester>
        <collage>MPCT</collage>
        <city>Gwalior</city>
        <state>Madhya Pradesh</state>
    </students>
</records>

First we will take the reference of the TextView from the layout file, set a local variable with the name of the file.

After that we will get the data from the asset folder like this:

InputStream I = getAssets().open("Students.xml");

We will that all the data from this InputStream and store them separately into strings and set that string in the TextView.

1) Java file:

package com.example.hp.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;


public class MainActivity extends AppCompatActivity
{
	TextView T;
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		T=(TextView)findViewById(R.id.textView);
		try{
			InputStream I = getAssets().open("Students.xml");
			DocumentBuilderFactory D=DocumentBuilderFactory.newInstance();
			DocumentBuilder d=D.newDocumentBuilder();
			Document mydocument =d.parse(I);
			// to get the elements from document 'mydocument'
			Element E=mydocument.getDocumentElement();
			E.normalize();
			NodeList MyListOfElemnts = mydocument.getElementsByTagName("students");
			for (int i=0;i<MyListOfElemnts.getLength();i++)
			{
				Node N = MyListOfElemnts.item(i);
				Element myElement = (Element) N;
				NodeList N1 = myElement.getElementsByTagName("name").item(i).getChildNodes();
				Node node1 = N1.item(i);
				String name = node1.getNodeValue();
				NodeList N2 = myElement.getElementsByTagName("course").item(i).getChildNodes();
				Node node2 = N2.item(i);
				String course = node2.getNodeValue();
				NodeList N3 = myElement.getElementsByTagName("semester").item(i).getChildNodes();
				Node node3 = N3.item(i);
				String semester = node3.getNodeValue();
				NodeList N4 = myElement.getElementsByTagName("collage").item(i).getChildNodes();
				Node node4 = N4.item(i);
				String collage = node4.getNodeValue();
				NodeList N5 = myElement.getElementsByTagName("city").item(i).getChildNodes();
				Node node5 = N5.item(i);
				String city = node5.getNodeValue();
				NodeList N6 = myElement.getElementsByTagName("state").item(i).getChildNodes();
				Node node6 = N6.item(i);
				String state = node6.getNodeValue();
				T.setText("Name: "+name+"\nCourse: "+course+"\nSemester: " + semester+"\nCollage: "+collage+"\nCity: "+city+"\nState: " + state);
			}
		}
		catch(Exception exception)
		{
			exception.printStackTrace();}
		}
	}
}

2) XML file:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.hp.myapplication.MainActivity">


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true" />
</RelativeLayout>

3) Students.xml file:

<?xml version="1.0"?>
    <records>
    <students>
        <name>Manu Jemini</name>
        <course>B.E.</course>
        <semester>6</semester>
        <collage>MPCT</collage>
        <city>Gwalior</city>
        <state>Madhya Pradesh</state>
    </students>
</records>

4) Android Manifest file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.hp.myapplication">
<uses-permission android:name="android.permission.CALL_PHONE"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        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>

Output

Parse an XML file in Android






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.