You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin结合SimpleXML解析XML遇ElementList匹配失败问题求助

问题解决:Kotlin + SimpleXML 解析XML的ValueRequiredException错误

核心错误点与修正方案

你的代码存在两个关键错误导致解析失败:

  1. @Root注解位置错误
    SimpleXML的@Root是类级别的注解,用于标记XML根节点对应的实体类,不能用@field:限定符放在字段上。

  2. ElementList的inline参数设置错误
    你的XML结构是<channels>节点包裹多个<channel>,而inline=true会让解析器直接在根节点下寻找<channel>,忽略<channels>容器,这和你的XML结构不匹配,必须改为inline=false。

修正后的实体类代码

@Root(strict = false, name = "serverConfiguration")
class ServerConfiguration {   
    @ElementList(required = true, name = "channels", entry = "channel", inline = false, type = Channel::class)
    var channels: List<Channel> = emptyList()

    @Element(name = "serverSettings", required = true, type = ServerSettings::class)
    lateinit var serverSettings: ServerSettings
}

补充说明

  • 移除lateinit改用默认空集合emptyList(),可以避免SimpleXML初始化字段时的潜在问题,同时保持required=true确保必须存在<channels>节点。
  • 确保你的Channel和ServerSettings类也正确配置了SimpleXML注解,示例如下:
@Root(name = "channel", strict = false)
class Channel {
    // 根据你的XML结构调整字段与注解
    @Element(name = "channelId")
    var id: String = ""
}

@Root(name = "serverSettings", strict = false)
class ServerSettings {
    // 根据你的XML结构调整字段与注解
    @Element(name = "listenPort")
    var port: Int = 0
}

验证代码

你的序列化代码无需修改,保持原样即可:

val serializer: Serializer = Persister()
val dataFetch = serializer.read(ServerConfiguration::class.java, myFile!!, false)

内容的提问来源于stack exchange,提问作者K. K.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 20:10:40