Skip to main content

Parsing XML using Retrofit

Developing our own type-safe HTTP library to interface with a REST API can be a real pain as we have to handle many aspects -
  • making connections
  • caching
  • retrying failed requests
  • threading
  • response parsing
  • error handling, and more. 
Retrofit, on the other hand, is a well-planned, documented and tested library that will save you a lot of precious time and headaches. In this tutorial, we are going to discuss how we can parse the XML response returned from using the Retrofit library.

To work with Retrofit, we need three classes - 
  • Model class to map the JSON data
  • Interfaces which defines the possible HTTP operations
  • Retrofit.Builder class - Instance which uses the interface and the Builder API which allows defining the URL endpoint for the HTTP operation.
Every method of the above interface represents on possible API call. The request type is specified by using appropriate annotations (GET, POST). The response is returned as a Call object.
So, without any further delays, let's get our hands dirty with some code.

Project setup 

To create a project in Eclipse IDE, follow below steps - 
  1. Navigate to File ⇨ New ⇨ Project ⇨ Maven ⇨ Maven Project ⇨ Next
  2. Select archetype for the maven project and then Next
  3. Add project details and click on Finish. 
  4. Now add following dependencies in the pom.xml file.

Sample XML

A sample XML RSS feed response looks likes

Code in Action

First, we need to create the model classes - one for each article and other for the feed. Let's first create a class for the article.

Let us understand the code now. We have used different annotations in this class

  1. @Root - This indicates that the class is serialized/deserialized. It represents the element in the XML. The name property signifies the element name. If it is not defined, then the class name is used as the element name. With strict set to false, strict parsing is disabled. This tells the parser to not fail and throw an exception if an XML element or attribute is found for which no mapping is provided.
  2. @Element - It represents an XML element. If no name is specified, the field name will be used.
Now, let us create the model class for the RSS feed.
Some other annotations used are
  1. @ElementList - This indicates the collection is being used. With inline set to true, it is determined that the elements of the Collection are inlined. That means, that they have no enclosing element and are listed one after another within the XML response.
  2. @Path - We can provide a path to an XML element inside the XML tree.
Now, after creating the models, let's expose the API via an interface.

To call the API, let'ss create a controller that creates a Retrofit client and handles the result.
Now, to run this application below is the main class


After running the application, the output will be as below

Channel Title: Times of India

Title: RS Dy chair poll: BJD, TRS boost to NDA; oppn questions Cong strategy

Title: Kerala rains live: 26 dead, CM says situation grim

Title: AAP won't join oppn alliance for LS polls: Kejriwal

Title: Samsung launches Galaxy Note 9: Specs and more

Title: US-China trade war may bring cheaper oil to India


Thus, we have seen that it is very easy to parse the XML response using the Retrofit library. A lot of boilerplate code has been eliminated. This increases the faster time to market and maintenance of code becomes very easy. You can find the complete code on GitHub
That's it for today. I hope you enjoyed this post. Happy Coding!! 😊


Popular posts from this blog

Threads in Java - Masterclass (Part 0)

Threads in Java Multithreading is a way to introduce concurrency in a program. In any case, if there are parallel paths in our program (parts which do not depend on the result from another part), we can make use of multithreading. One should exploit this feature, especially with all these multiple core machines nowadays. Below are a few reasons why we should use multithreading - 1. Keep a process responsive There was once a time when you would print a document in MS Word and the application would freeze for an annoyingly long amount of time until the job finished. Eventually, Microsoft solved this problem by running a printing job parallel to the main thread/ GUI thread.  To be clear though, not only GUI apps but Network services have to keep an ear to the ground for new clients, dropped connections and cancellation requests. In either case, it is critical to do the heavy lifting on a secondary thread to keep the user satisfied. 2. Keep a processor busy Keeping a proc

Material design profile page in Android

Hey everyone, some days back I was working on one my personal Android project. In that project, I was supposed to create a simple profile page for a user. This profile page was supposed to show some basic details of a user. The output of this UI will be like this - Profile page screen I created the profile page using material design and in this post, I am going to discuss a step by step tutorial to create a simple yet elegant profile page. Without further ado, let's get started. Creating a new project Click on File ➤ New Project ➤ Empty Activity and fill the necessary details. Change styles.xml file Navigate to app\src\main\res\values\styles.xml Change the style value from DarkActionBar to NoActionBar as below <resources> <!-- Base application theme. --> <style name= "AppTheme" parent= "Theme.AppCompat.Light.NoActionBar" > <!-- Customize your theme here. --> <item name= "colorPr