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

Android Kotlin中SimpleXmlConverterFactory读取XML节点属性崩溃无日志

问题原因

  • 子元素实体类Destination缺失@Root注解,SimpleXml要求所有参与XML解析的自定义实体类都需要标注该注解才能被识别为可解析的节点类。
  • Destination类的属性均为只读val类型,SimpleXml解析过程中需要向属性写入解析结果,无法对只读属性赋值会引发底层解析异常。
  • Kotlin属性直接标注注解默认作用于Kotlin专属的property元数据,SimpleXml无法识别,需要显式指定注解作用于字段/ getter方法。
  • 无日志输出是因为Retrofit的解析异常会被包装在回调的onFailure方法的异常参数中,你没有打印异常栈导致看不到具体报错信息。

修复方案

1. 修正Destination类代码

// 新增@Root注解标注为可解析节点
@Root(name = "Destination", strict = false)
class Destination @JvmOverloads constructor() {
    // 改为var可写属性,指定注解作用于getter让SimpleXml识别
    @get:Attribute(name = "id", required = false)
    var id: String? = null

    @get:Text(required = false)
    var destinationContent: String? = null
}

2. 修正SearchResultsWrapper中的Destination属性注解

@Root(name = "HotelSearchRES", strict = false)
class SearchResultsWrapper @JvmOverloads constructor() {
    // 指定注解作用于字段,避免Kotlin注解作用域问题
    @field:Element(name = "Destination")
    var destination: Destination? = null

    // 其余属性保持不变,如果后续需要解析City的id属性,也可以参照Destination类改造City对应的实体
    @set:Element(name = "City")
    @get:Element(name = "City")
    var city: String? = null

    @set: Element(name = "Currency")
    @get: Element(name = "Currency")
    var currency: Int? = null

    @set: Element(name = "Language")
    @get: Element(name = "Language")
    var language: Int? = null

    @set: Element(name = "FromDate")
    @get: Element(name = "FromDate")
    var fromDate: String? = null

    @set: Element(name = "ToDate")
    @get: Element(name = "ToDate")
    var toDate: String? = null
}

3. 补充日志排查逻辑

在Retrofit请求的onFailure回调中添加异常栈打印代码,后续出现问题时可快速定位原因:

override fun onFailure(call: Call<SearchResultsWrapper>, t: Throwable) {
    t.printStackTrace() // 打印异常栈即可看到SimpleXml的具体解析报错
    // 其余异常处理逻辑
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 04:24:06