忽略SimpleXML Path注释

时间:2018-05-27 09:16:52

标签: android xml xpath kotlin simple-framework

我想知道Simplexml的@Path注释如何适用于Android上的kotlin(或者如果它可以工作则更好)。

给定的XML将演示问题

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<start >
    <one>never</one>
    <firstlevel>
        <secondlevel>
            <one>always</one>
            <testelement>1</testelement>
            <testlist>
                <title>1</title>
                <active>false</active>
            </testlist>
            <testlist>
                <title>2</title>
                <active>false</active>
            </testlist>
            <testlist>
                <title>3</title>
                <active>false</active>
                <testobject>
                    <testbyte>127</testbyte>
                </testobject>
            </testlist>
        </secondlevel>
    </firstlevel>
</start>

和对象

@Root(name = "start", strict = false)
data class Baseobj constructor(

    @field:ElementList(name = "testlist", inline = true, required = false)
    @param:ElementList(name = "testlist", inline = true, required = false)
    @Path("firstlevel/secondlevel")
    var testlist: List<testlist>? = listOf(),

    @field:Element(name = "testelement", required = false)
    @param:Element(name = "testelement", required = false)
    @Path("firstlevel/secondlevel")
    var testelement: String? = null,

    @Path("firstlevel/secondlevel")
    @field:Element(name = "one", required = false)
    @param:Element(name = "one", required = false)
    var one: String? = null
)

相应的课程

@Root(strict = false, name = "testlist")
data class testlist constructor(
    @field:Element(required = false, name = "title")
    @param:Element(required = false, name = "title")
    var title: String? = null,


    @field:Element(required = false, name = "active")
    @param:Element(required = false, name = "active")
    var active: String? = null
)

使用测试

@Test
fun should_ParseTestXML() {
    val serializer = Persister()
    val stream = javaClass.getResourceAsStream("/raw/test.xml")
    val base = serializer.read(Baseobj::class.java, stream)

    println("Here we are: ${base.testelement} ${base.one}")
}

将打印出"Here we are: null never",这不是预期的行为,或者至少是预期行为。改装软件包

包含SimpleXML
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-jackson:2.4.0'
implementation('com.squareup.retrofit2:converter-simplexml:2.4.0') {
    exclude group: 'stax', module: 'stax-api'
    exclude group: 'stax', module: 'stax'
    exclude group: 'xpp3', module: 'xpp3'
}

在我当前的项目中,xml要复杂得多,对象结构不应该包含包装对象。尽管我知道存在转换器,但我希望有一个基于XPath用法的解决方案。

提前谢谢

迈克尔

1 个答案:

答案 0 :(得分:0)

简单的解决方案:

    @field:Path("firstlevel/secondlevel")
    @param:Path("firstlevel/secondlevel")

这声明了基于java的framesworks

的注释