SimpleXML:反序列化项目列表

时间:2019-03-01 10:02:37

标签: android xml kotlin simple-framework

我有这个XML要使用simpleXML反序列化

<Content>
    <Items count="2">
        <Device>
            <User>
                <Lastname>Straw</Lastname>
                <Firstname>Jim</Firstname>
            </User>
        </Device>
        <Device>
            <User>
                <Lastname>Straw</Lastname>
                <Firstname>John</Firstname>
            </User>
        </Device>
    </Items>
</Content>

我已经在Kotlin中创建了这个POJO,但是它与XML不匹配

@Root
data class Content(@field:ElementList(entry="Device") var device: List<Device>)

@Root
data class Device(@field:Element(name="User") var user: User? = null, 
    @field:Element(name="InvDevice") var invDevice: InvDevice? = null)

@Root
data class User(@field:Element(name="Lastname") var lastname: String? = null,
    @field:Element(name="Firstname") var firstname: String? = null)

我有一个ElementException:元素“ Items”在类中不匹配

1 个答案:

答案 0 :(得分:0)

按照建议here使用Android Studio中的POJO Generator插件,我发现了如何制作数据类

@Root
data class Content(@field:Element(name = "Items", required = false) var items: Items? = null)

data class Items(
    @field:ElementList(name = "Device", required = false, entry = "Device", inline = true)
    var deviceList: List<Device>? = null,
    @field:Attribute(name="count", required = false)
    var count: Int? = null
)

data class Device(@field:Element(name="User", required = false) var user: User? = null)

data class User(@field:Element(name="Lastname", required = false) var lastname: String? = null,
                @field:Element(name="Firstname", required = false) var firstname: String? = null)