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!! 😊


Post a Comment

Popular posts from this blog

Threads in Java - CountDownLatch (Part 12)

A CountDownLatch is a synchronizer which allows one thread to wait for one or more threads before starts processing. A good application of  CountDownLatch is in Java server-side applications where a thread cannot start execution before all the required services are started. Working A  CountDownLatch is initialized with a given count which is the number of threads it should wait for. This count is decremented by calling countDown() method by the threads once they are finished execution. As soon as the count reaches to zero, the waiting task starts running. Code Example Let us say we require three services, LoginService, DatabaseService and CloudService to be started and ready before the application can start handling requests. Output Cloud Service is up! Login Service is up! Database Service is up! All services are up. Now the waiting thread can start execution. Here, we can see that the main thread is waiting for all the three services to start before starting its own

I/O in Java - Masterclass (Part 0)

IO in Java Java input and output processes the input and produces the output based on the input. Java uses streams to perform input and output operations. In this masterclass on I/O, we will learn about the nitty gritty details of the File IO/NIO with lots of code examples. You can follow the below trail to dive deep into Java I/O Part 1 - Basics Part 2 - IO vs. NIO Part 3 - try-with-resources Part 4 - Directory Operations Part 5 - File Operations Part 6 - Temporary File Operations All of these posts include code examples to understand the concept. You can find the code of these examples on my  GitHub  repository. Feel free to fork or open issues, if any. I would love to hear your thoughts on this and would like have suggestions from you to make it better.  Feel free to befriend me on  Facebook ,  Twitter  or  Linked In  or say Hi by  email . Happy Coding 😊