使用简单XML解析XML [Java Android]

问题描述 投票:0回答:2

如何解析这个XML:

<resources> 
    <string name="name1">content1</string> 
    <string name="name2">content2</string> 
    <string name="name3">content3</string> 
    ...
</resources> 

我无法使用正确的注释创建对象来检索名称和内容。

我目前的工作:

@Root(name = "resources")
public class Translation {

    @ElementList(inline = true)
    private List<TranslationName> translationNames;

    public List<TranslationName> getTranslationNames() {
        return translationNames;
    }
}

@Root(name = "string")
public class TranslationName {

    @Attribute(name = "name")
    private String name;
    @Element(name = "string")
    private String content;

    public String getName() {
        return name;
    }

    public String getContent() {
        return content;
    }
}

但是我有:

无法在字段'content'上满足@ org.simpleframework.xml.Element(data = false,name = string,required = true,type = void)

编辑:

有了这个我成功恢复了内容:

@Root(name = "resources")
public class Translation {

    @ElementList(inline = true)
    private List<String> contentNames;

    public List<String> getContentNames() {
        return contentNames;
    }
}

但是,两者结合起来并不起作用:

@Root(name = "resources")
public class Translation {

    @ElementList(inline = true)
    private List<TranslationName> translationNames;
    @ElementList(inline = true)
    private List<String> contentNames;

    public List<TranslationName> getTranslationNames() {
        return translationNames;
    }

    public List<String> getContentNames() {
        return contentNames;
    }
}
java android xml simple-framework
2个回答
0
投票

你的类给出了像xml一样的

 <resources>
   <string name="name1"> <string>content1</string>   </string>
   <string name="name2"> <string>content2</string>   </string>
   <string name="name3"><string>content3</string>   </string>
 </resources>

for content属性替换为:

@Text
    private String content;

0
投票

您可以自己简单地编写XML解析器代码,而不是尝试使用注释的神奇组合来实现某些功能。不要使用Stax / pull - 它太低级,难以直接使用而且容易出错。试试Konsume-XML

data class Resource(val name: String, val content: String)

val konsumer = """
<resources>
    <string name="name1">content1</string>
    <string name="name2">content2</string>
    <string name="name3">content3</string>
</resources>
""".trimIndent().konsumeXml()
val resources: List<Resource> = konsumer.child("resources") {
    children("string") {
        Resource(attributes["name"], text())
    }
}
println(resources)

将打印

[Resource(name=name1, content=content1), Resource(name=name2, content=content2), Resource(name=name3, content=content3)]
© www.soinside.com 2019 - 2024. All rights reserved.