Home > other >  Create Kotlin data class for xml
Create Kotlin data class for xml

Time:11-04

Can anyone help with creating a Kotlin data class to use with Retrofit and the simplexml converter for this seemingly simple xml?

<texts>
<text id="3">
<title>Veðurhorfur á höfuðborgarsvæðinu</title>
<creation>2022-11-03 10:20:30</creation>
<valid_from>2022-11-03 12:00:00</valid_from>
<valid_to>2022-11-05 00:00:00</valid_to>
<content>Norðlæg </content>
</text>
<text id="6">
<title>Veðurhorfur</title>
<creation>2022-11-03 08:41:53</creation>
<valid_from>2022-11-05 12:00:00</valid_from>
<valid_to>2022-11-10 12:00:00</valid_to>
<content>Austan- </content>
</text>
</texts>

CodePudding user response:

Based on this article, the following should work:

@Root(name = "texts", strict = false)
class Texts @JvmOverloads constructor(
    @field: ElementList(inline = true)
    var textList: List<Text>? = null
)

@Root(name = "text", strict = false)
class Text @JvmOverloads constructor(
    @field: Attribute(name = "id")
    var id: String = "",
    @field: Element(name = "title")
    var title: String = "",
    @field: Element(name = "creation")
    var creation: LocalDateTime = LocalDateTime.MIN,
    @field: Element(name = "valid_from")
    var validFrom: LocalDateTime = LocalDateTime.MIN,
    @field: Element(name = "valid_to")
    var validTo: LocalDateTime = LocalDateTime.MIN,
    @field: Element(name = "content")
    var content: String = "",
)
  • Related