Basic XML Parsing in Android

A small code snippet showing how to read values from an xml file in Android

Basic XML Parsing in Android
Photo by Jackson Sophat / Unsplash

Context

I recently had to parse some xml data in Android and thought - "this should be an easy one-liner" or something similar. I was wrong, there seemed to be a number of ways to do it and they were all more verbose than I would have liked. So this article is to show of the approach I ended up with; the best way I could find to parse simple xml in a simple way.

Input

Here is the sample of XML I want to extract values from

<feed>
    <entry>
        <title>Entry A</title>
        <updated>2022-11-06T07:25:52+11:00</updated>
        <link rel="alternate" type="text/html" href="https://my.url/A"/>
    </entry>
    <entry>
         <title>Entry B</title>
        <updated>2022-09-29T06:09:43+10:00</updated>
        <link rel="alternate" type="text/html" href="https://my.url/B"/>
    </entry>
</feed>
xmlString

Code

Here is a short function that shows how to extract the title, updated string, and link url from the first entry in the above xml. I use DOM Element and did not need to add any additional third party libraries to the application.

import org.w3c.dom.Element
import org.xml.sax.InputSource
import java.io.StringReader
import javax.xml.parsers.DocumentBuilderFactory
 
 fun parseRssValues(xmlString: String) {
 
        // Boilerplate required for parser
        val builderFactory = DocumentBuilderFactory.newInstance()
        val docBuilder = builderFactory.newDocumentBuilder()
        val inputSource = InputSource(StringReader(xmlString))
        val doc = docBuilder.parse(inputSource)
        
        // Grab the root 'feed' element
        val feed = doc.getElementsByTagName("feed").item(0) as Element
        
        // 'entry' is an array. Here I grab the first one
        val entry = feed.getElementsByTagName("entry").item(0) as Element
        
        // Retrieve simple text content
        val title = entry.getElementsByTagName("title").item(0).textContent
        val updated = entry.getElementsByTagName("updated").item(0).textContent
        
        // Retrieve data from an elements attribute
        val updateLink = entry.getElementsByTagName("link")
            .item(0).attributes.getNamedItem("href").textContent
            
}

More Information