Retrofit 2 – How to parse sitemap in android

Learn to parse sitemap in an android app using Retrofit 2 using xml parsing with simple xml converter dependency.

In this example, we will be reading and parsing the sitemap of this blog. A sample entry is given below:

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
	<url>
		<loc>https://howtodoinjava.com/retrofit2/retrofit-sync-async-calls/</loc>
		<lastmod>2019-08-25T22:22:39+00:00</lastmod>
		<changefreq>monthly</changefreq>
		<priority>0.8</priority>
	</url>
	...
	...
</urlset>

1. Dependency

To enable to parsing sitemap in android, we need at least two dependencies i.e. retrofit and converter-simplexml.

dependencies { 
    compile 'com.squareup.retrofit2:retrofit:2.6.1'
    compile 'com.squareup.retrofit2:converter-simplexml:2.6.1'
}
<dependency>
	<groupId>com.squareup.retrofit2</groupId>
	<artifactId>retrofit</artifactId>
	<version>2.6.1</version>
</dependency>
<dependency>
	<groupId>com.squareup.retrofit2</groupId>
	<artifactId>converter-simplexml</artifactId>
	<version>2.6.1</version>
</dependency>

2. Sitemap model

Start by creating model for consuming the sitemap entry items.

import java.util.ArrayList;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;

@Root(name = "urlset")
public class SitemapResponse 
{
	@ElementList(name = "url", inline = true)
	private ArrayList<SitemapEntry> url;

	@Override
	public String toString() {
		return "SitemapResponse [urlset=" + url + "]";
	}
}
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

@Root(name="url")
public class SitemapEntry 
{
	@Element(name="loc")
	private String loc;
	
	@Element(name="lastmod")
	private String lastmod;
	
	@Element(name="changefreq")
	private String changefreq;
	
	@Element(name="priority")
	private float priority;
	
	@Override
	public String toString() {
		return "SitemapEntry [loc=" + loc + ", lastmod=" + lastmod + ", 
				changefreq=" + changefreq + ", priority=" + priority
				+ "]";
	}
}

3. Sitemap service interface

Create service interface which will be invoked by retrofit to execute HTTP request. Notice the API URL is sitemap.xml.

import retrofit2.Call;
import retrofit2.http.GET;

public interface SitemapService 
{
	@GET("sitemap.xml") Call<SitemapResponse> getFeed();
}

4. Read sitemap example

Let’s create a retrofit instance and execute the sitemap request. Given example uses the async request example.

import java.io.IOException;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.simplexml.SimpleXmlConverterFactory;

public class SitemapServiceDemo 
{
	private static final String BASE_URL = "https://howtodoinjava.com/";

	private static Retrofit.Builder builder = new Retrofit.Builder().baseUrl(BASE_URL)
			.addConverterFactory(SimpleXmlConverterFactory.create());

	private static HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor()
			.setLevel(HttpLoggingInterceptor.Level.BODY);

	private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

	public static void main(String[] args) throws IOException 
	{
		httpClient.addInterceptor(loggingInterceptor);
		builder.client(httpClient.build());

		Retrofit retrofit = builder.build();

		SitemapService SitemapService = retrofit.create(SitemapService.class);

		Call<SitemapResponse> callAsync = SitemapService.getFeed();

		callAsync.enqueue(new Callback<SitemapResponse>() {
			@Override
			public void onResponse(Call<SitemapResponse> call, Response<SitemapResponse> response) {
				if (response.isSuccessful()) {
					SitemapResponse apiResponse = response.body();
					// API response
					System.out.println(apiResponse);
				} else {
					System.out.println("Request Error :: " + response.errorBody());
				}
			}

			@Override
			public void onFailure(Call<SitemapResponse> call, Throwable t) {
				if (call.isCanceled()) {
					System.out.println("Call was cancelled forcefully");
				} else {
					System.out.println("Network Error :: " + t.getLocalizedMessage());
				}
			}
		});
	}
}

Program output.

SitemapResponse [urlset=
		[SitemapEntry [loc=https://howtodoinjava.com/ 
					retrofit2/retrofit-sync-async-calls/, 
		lastmod=2019-08-25T22:22:39+00:00, 
		changefreq=monthly, 
		priority=0.8].
		...
		...
		...

Drop me your questions related to reading sitemap in android app using Retrofit 2.

Happy Learning !!

Was this post helpful?

Join 8000+ Awesome Developers, Like YOU!

Leave a Comment

About HowToDoInJava

This blog provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.