簡體   English   中英

使用簡單XML解析XML [Java Android]

[英]Parse XML with Simple XML [Java Android]

如何解析此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;
    }
}

您的班級給xml像

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

內容屬性替換為:

@Text
    private String content;

您可以嘗試自己編寫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)]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM