SimpleXML 转换器的问题 - PersistenceException

Posted

技术标签:

【中文标题】SimpleXML 转换器的问题 - PersistenceException【英文标题】:Problem with SimpleXML Converter - PersistenceException 【发布时间】:2021-12-03 06:34:59 【问题描述】:

我尝试使用 XML SimpleXML Converter 解析从 https://www.w3schools.com/xml/simple.xml 获得的 xml,但出现异常

org.simpleframework.xml.core.PersistenceException:构造函数与类 com.example.nbrbcurrency.retrofit.models.Food 不匹配

我的 POJO 的

import org.simpleframework.xml.ElementList
import org.simpleframework.xml.Root

@Root(strict = false, name = "breakfast_menu")
data class BreakFastMenu @JvmOverloads constructor(
    @field:ElementList(inline = true)
    var foodList : List<Food>
)

import org.simpleframework.xml.Element
import org.simpleframework.xml.Root

@Root(name = "food")
data class Food @JvmOverloads constructor(
    @field:Element(name = "name")
    var name: String,

    @field:Element(name = "price")
    var price: String,

    @field:Element(name = "description")
    var description: String,

    @field:Element(name = "calories")
    var calories: String)

xml

<breakfast_menu>
<food>
<name>Belgian Waffles</name>
<price>$5.95</price>
<description>Two of our famous Belgian Waffles with plenty of real maple syrup</description>
<calories>650</calories>
</food>
<food>
<name>Strawberry Belgian Waffles</name>
<price>$7.95</price>
<description>Light Belgian waffles covered with strawberries and whipped cream</description>
<calories>900</calories>
</food>
<food>
<name>Berry-Berry Belgian Waffles</name>
<price>$8.95</price>
<description>Light Belgian waffles covered with an assortment of fresh berries and whipped cream</description>
<calories>900</calories>
</food>
<food>
<name>French Toast</name>
<price>$4.50</price>
<description>Thick slices made from our homemade sourdough bread</description>
<calories>600</calories>
</food>
<food>
<name>Homestyle Breakfast</name>
<price>$6.95</price>
<description>Two eggs, bacon or sausage, toast, and our ever-popular hash browns</description>
<calories>950</calories>
</food>
</breakfast_menu>

【问题讨论】:

【参考方案1】:

我自己解决了。我只是预定义了属性。

import org.simpleframework.xml.Attribute
import org.simpleframework.xml.ElementList
import org.simpleframework.xml.Root

@Root(strict = false, name = "DailyExRates")
data class CurrencyDataList constructor(
    @field:Attribute(name = "Date")
    var date: String = "",
    @field:ElementList(inline = true)
    var currencies: List<CurrencyData> = ArrayList()
)

【讨论】:

以上是关于SimpleXML 转换器的问题 - PersistenceException的主要内容,如果未能解决你的问题,请参考以下文章

Java - 将xml转换为JAVA Pojo类,包括java注释(Simplexml)

使用属性包含斜杠的 simplexml_load_string 将 XML 转换为数组

如何使用合法的 XML 将数组转换为 SimpleXML [重复]

PHP SimpleXML 中的 XML 到 JSON 转换

simplexml_load_string 转换xml为数组

xml 元素中的属性不在 simplexml 数组中