pretty

Monday 9 January 2023

Parsing XML response from service on Android without using extra libraries

The XML response from REST services is not commonplace, and today it is problematic to parse it using Retrofit or Ktor on Android. While Retrofit has the SimpleXmlConverterFactory, this library is deprecated, and no viable alternatives exist. Ktor on the other hand, has XML Converter only server side.

The solution presented in this code snippet uses built-in Android DocumentBuilder to process the XML. This class is available in Android since API Level 1. In the following sample, the application needs to fetch a list of photos from Flickr service. This service provides the XML formatted response. We are only interested in populating our FlickrPhotoModel data classes with the attributes from <photo> nodes.


While this approach may not be ideal if we need to work extensively with XML API, it is a proper fallback to use for just a bunch of requests.