In This Tutorial we will Discuss About Xml Parsing. XML is a acronym of Extensible Markup Language a document formatting language used for some World Wide Web Pages. This language is some what similar to Html but XML is extensible that means in html we can not add new Tags or new elements but in XML we can do all that very easily. That's why XML Came in MainStream.
Their are Two major Parsing methods used in Android
i. Json Parsing
ii. Xml Parsing
I already Published an article on RecyclerView and Webview if you haven't practice I must suggest you check that. RecyclerView Example, Webview Example
This will be our Response of XML
I Get this Output by a News website in XML format, anyone can use their link they have an Open Platform.
Let's Understand the Response
So, guys Lets start,
1. Create a new Project by Going to File ⇒ New Android Project. Fill all the Details and Name your Activity as MainActivity.
2. Once your Project is created successfully open your activity_main.xml file and Add Below Code.
To Populate data in Recycler view we have to Make a POJO class Name it as FeedItem.java
3. Create a POJO class FeedItem.java and Add Below Code
To Display Data we have to create a custom layout for recylerview so we can decide how every single Item will display on the screen.
So create a layout file, I ready discussed how to create a layout file in the previous tutorial of recyclerview
4. Create a layout file and add below code into that
Here we are getting a Link ,in our response, to read the full news. so we have to open that link in Webview so for that we have to create a new Activity which Contains WebView and can open our Link.
I already covered a brief tutorial on Webview you can check it out fromhere.
5. Create a new Activity Name it as WebViewActivity.java and add below xml code in activity_web_view.xml
7. Create an Adapter For RecyclerView name it as MyRVAdapter.java
8. Now finally Come to MainActivity.java and Call the HTTP Request to get the Response and Parse it
9. Add a Internet Permission into AndroidManifest.xml
10. Now run your Project you will see a below output
For More Awesome Tutorial on Android Subscribe to My Blog and Share this with all your Colleague.
Thank You
Their are Two major Parsing methods used in Android
i. Json Parsing
ii. Xml Parsing
Use XML over JSON when any of these is true:
- You need message validation
- You're using XSLT
- Your messages include a lot of marked-up text
- You need to interoperate with environments that don't support JSON
I already Published an article on RecyclerView and Webview if you haven't practice I must suggest you check that. RecyclerView Example, Webview Example
This will be our Response of XML
<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:media="http://search.yahoo.com/mrss/">
<channel>
<title>Latest News from Science Magazine</title>
<link>http://www.sciencemag.org/rss/news_current.xml</link>
<description>Editable in modal at Format : RSS Feed | Settings : RSS Description</description>
<pubDate>Wed, 11 Oct 2017 05:51:21 -0400</pubDate>
<item>
<title><![CDATA[The big city is safer than the country, at least if you’re a goose]]></title>
<link>http://www.sciencemag.org/news/2017/10/big-city-safer-country-least-if-you-re-goose</link>
<pubDate>Wed, 11 Oct 2017 12:00:00 -0400</pubDate>
<guid isPermaLink="true">http://www.sciencemag.org/news/2017/10/big-city-safer-country-least-if-you-re-goose?rss=1</guid>
<description><![CDATA[City birds are twice as likely to survive the winter than their country cousins]]></description>
<media:credit role="author"><![CDATA[Lakshmi Supriya]]></media:credit>
<media:category><![CDATA[Biology, Climate, Plants & Animals]]></media:category>
<media:content url="http://www.sciencemag.org/sites/default/files/styles/article_main_teaser/public/cc_C31FJ4_16x9.jpg?itok=ZBt2Ej2a" height="266" width="127" />
<media:thumbnail url="http://www.sciencemag.org/sites/default/files/styles/article_main_teaser/public/cc_C31FJ4_16x9.jpg?itok=ZBt2Ej2a" height="266" width="127" />
</item>
<item>
<title><![CDATA[Watch the human genome fold itself in four dimensions ]]></title>
<link>http://www.sciencemag.org/news/2017/10/watch-human-genome-fold-itself-four-dimensions</link>
<pubDate>Tue, 10 Oct 2017 09:00:00 -0400</pubDate>
<guid isPermaLink="true">http://www.sciencemag.org/news/2017/10/watch-human-genome-fold-itself-four-dimensions?rss=1</guid>
<description><![CDATA[Loops form and disappear to allow genes to interact]]></description>
<media:credit role="author"><![CDATA[Elizabeth Pennisi]]></media:credit>
<media:category><![CDATA[Biology, Health]]></media:category>
<media:content url="http://www.sciencemag.org/sites/default/files/styles/article_main_teaser/public/4dchromevideo.jpg?itok=Q73Ntn43" height="266" width="127" />
<media:thumbnail url="http://www.sciencemag.org/sites/default/files/styles/article_main_teaser/public/4dchromevideo.jpg?itok=Q73Ntn43" height="266" width="127" />
</item>
</channel>
</rss>
I Get this Output by a News website in XML format, anyone can use their link they have an Open Platform.
Let's Understand the Response
So, guys Lets start,
1. Create a new Project by Going to File ⇒ New Android Project. Fill all the Details and Name your Activity as MainActivity.
2. Once your Project is created successfully open your activity_main.xml file and Add Below Code.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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.targetandroid.info.xmlfeed.MainActivity">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/rv_feed" >
</android.support.v7.widget.RecyclerView>
</LinearLayout>
To Populate data in Recycler view we have to Make a POJO class Name it as FeedItem.java
3. Create a POJO class FeedItem.java and Add Below Code
/**
* Created by Faizan on 09/04/17.
*/
public class FeedItem {
String title;
String link;
String description;
String pubDate;
String thumbnailUrl;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPubDate() {
return pubDate;
}
public void setPubDate(String pubDate) {
this.pubDate = pubDate;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
}
}
To Display Data we have to create a custom layout for recylerview so we can decide how every single Item will display on the screen.
So create a layout file, I ready discussed how to create a layout file in the previous tutorial of recyclerview
4. Create a layout file and add below code into that
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:paddingTop="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tv_title"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tv_desc"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tv_pubdate"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tv_link"
android:textColor="@android:color/holo_blue_dark"
/>
</LinearLayout>
Here we are getting a Link ,in our response, to read the full news. so we have to open that link in Webview so for that we have to create a new Activity which Contains WebView and can open our Link.
I already covered a brief tutorial on Webview you can check it out fromhere.
5. Create a new Activity Name it as WebViewActivity.java and add below xml code in activity_web_view.xml
<LinearLayout 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:orientation="vertical"
tools:context="com.targetandroid.info.xmlfeed.WebViewActivity">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/wv_url" >
</WebView>
</LinearLayout>
6. Now open WebViewActivity.java and add below codeimport android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebViewActivity extends AppCompatActivity {
String webviewurl;
WebView wv_url;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
//here we will get the url passed by previous activity
webviewurl=getIntent().getStringExtra("url");
wv_url=(WebView)findViewById(R.id.wv_url);
wv_url.setWebViewClient(new WebViewClient());
//load the url in Webview
wv_url.loadUrl(webviewurl);
}
}
7. Create an Adapter For RecyclerView name it as MyRVAdapter.java
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
/**
* Created by Faizan on 09/19/17.
*/
public class MyRVAdapter extends RecyclerView.Adapter<MyRVAdapter.MyViewHolder> {
private List<FeedItem> feedItems;
private Context context;
public MyRVAdapter(Context context,List<FeedItem> items){
this.context=context;
this.feedItems = items;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
final View view = inflater.inflate(R.layout.customlayout, parent, false);
MyViewHolder mvh = new MyViewHolder(view, new MyViewHolder.myClickWebView() {
@Override
public void gotoWebView(String textlink) {
Intent intent=new Intent(context,WebViewActivity.class);
//Send the url to webviewActivity
intent.putExtra("url",textlink);
context.startActivity(intent);
}
});
return mvh;
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
FeedItem item = feedItems.get(position);
holder.tv_desc.setText(item.getDescription());
holder.tv_link.setText(item.getLink());
holder.tv_pubdate.setText(item.getPubDate());
holder.tv_title.setText(item.getTitle());
//get the link
holder.textlink=item.getLink();
}
@Override
public int getItemCount() {
return feedItems==null?0:feedItems.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView tv_title, tv_desc, tv_pubdate, tv_link;
String textlink;
myClickWebView myClickWebView;
public MyViewHolder(View itemView, final myClickWebView myClickWebView) {
super(itemView);
tv_title=(TextView)itemView.findViewById(R.id.tv_title);
tv_desc=(TextView)itemView.findViewById(R.id.tv_desc);
tv_pubdate=(TextView)itemView.findViewById(R.id.tv_pubdate);
tv_link=(TextView)itemView.findViewById(R.id.tv_link);
this.myClickWebView=myClickWebView;
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
myClickWebView.gotoWebView(textlink);
}
});
/* tv_link.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(context,WebViewActivity.class);
}
});*/
}
//interface to handle onclick event and send some extras to another activity
public interface myClickWebView{
void gotoWebView(String textlink);
}
}
}
8. Now finally Come to MainActivity.java and Call the HTTP Request to get the Response and Parse it
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
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 java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
public class MainActivity extends AppCompatActivity {
ArrayList<FeedItem> feedItems=new ArrayList<>();
RecyclerView rv_test;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rv_test=(RecyclerView) findViewById(R.id.rv_test);
ReadRss readRss=new ReadRss(this);
//call Http request using Async Task
readRss.execute();
}
public class ReadRss extends AsyncTask<Void, Void, Void> {
Context context;
String address = "http://www.sciencemag.org/rss/news_current.xml";
ProgressDialog progressDialog;
URL url;
public ReadRss(Context context) {
this.context = context;
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Loading...");
}
@Override
protected void onPreExecute() {
progressDialog.show();
super.onPreExecute();
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.dismiss();
}
@Override
protected Void doInBackground(Void... params) {
ProcessXml(Getdata());
//Every View run on Ui Thread and doInBackground runs in Background thread
runOnUiThread(new Runnable() {
@Override
public void run() {
rv_test.setAdapter(new MyRVAdapter(MainActivity.this,feedItems));
rv_test.setLayoutManager(new LinearLayoutManager(MainActivity.this, LinearLayoutManager.VERTICAL, false));
}
});
return null;
}
//Parse the XML response and Pass it to Recycler View
private void ProcessXml(Document data) {
if (data != null) {
Element root = data.getDocumentElement();
Node channel = root.getChildNodes().item(1);
NodeList items = channel.getChildNodes();
for (int i = 0; i < items.getLength(); i++) {
Node cureentchild = items.item(i);
if (cureentchild.getNodeName().equalsIgnoreCase("item")) {
FeedItem item=new FeedItem();
NodeList itemchilds = cureentchild.getChildNodes();
for (int j = 0; j < itemchilds.getLength(); j++) {
Node cureent = itemchilds.item(j);
if (cureent.getNodeName().equalsIgnoreCase("title")){
item.setTitle(cureent.getTextContent());
}else if (cureent.getNodeName().equalsIgnoreCase("description")){
item.setDescription(cureent.getTextContent());
}else if (cureent.getNodeName().equalsIgnoreCase("pubDate")){
item.setPubDate(cureent.getTextContent());
}else if (cureent.getNodeName().equalsIgnoreCase("link")){
item.setLink(cureent.getTextContent());
}
}
feedItems.add(item);
Log.d("itemTitle", item.getTitle());
Log.d("itemDescription",item.getDescription());
Log.d("itemPubDate",item.getPubDate());
Log.d("itemLink",item.getLink());
}
}
}
}
//Call the Http GET Request and
//Return the XML response in Document Format
public Document Getdata() {
try {
url = new URL(address);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
InputStream inputStream = connection.getInputStream();
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDoc = builder.parse(inputStream);
return xmlDoc;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
}
9. Add a Internet Permission into AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
10. Now run your Project you will see a below output
For More Awesome Tutorial on Android Subscribe to My Blog and Share this with all your Colleague.
Thank You



EmoticonEmoticon