Ken
Ken

Reputation: 109

Parse RSS XML with Kotlin

This is my data class of Kotlin. I'd like to parse RSS but I got a message like 'item' does not have a match in class...

@Root(name = "channel", strict = false)
data class ArticleList(
    @ElementList(name = "item", inline = true)
    val articleList: List<Article>
)

@Root(name = "item", strict = false)
data class Article(
    @Element(name="title")
    val title: String
)

Could somebody help me to parse RSS? For example, https://learningenglish.voanews.com/api/zkm-qem$-o

If I want to get all title tags under item tag, how do you write the code?

Upvotes: 0

Views: 1270

Answers (1)

Kafka Wanna Fly
Kafka Wanna Fly

Reputation: 53

RSS-Parser could help you do this. In your build.gradle:

dependencies {
    implementation 'com.prof18.rssparser:rssparser:3.1.3'
}

How to use:

fun fetchRssData() : ArrayList<String> {
        val parser = Parser.Builder()
            .context(this)
            .charset(Charset.forName(StandardCharsets.UTF_8.name()))
            .cacheExpirationMillis(24L * 60L * 60L * 100L) // one day
            .build()

        val titleList = arrayListOf<String>();

        runBlocking {
            launch {
                val chanel = parser.getChannel(url = "https://learningenglish.voanews.com/api/zkm-qem$-o")
                Log.d("MyChanel", chanel.toString())

                for (art in chanel.articles) {
                    titleList.add(art.title!!)
                }
            }
        }

        return titleList
    }

Note: This seems work fine with English but not good in Vietnamese.

Upvotes: 1

Related Questions