求创建适配Retrofit与SimpleXML的Kotlin数据类解析指定XML
适配Retrofit与SimpleXML转换器的Kotlin数据类实现
第一步:添加必要依赖
在Gradle配置文件中引入以下依赖,确保Retrofit和SimpleXML转换器能正常协作:
// Retrofit核心库 implementation 'com.squareup.retrofit2:retrofit:2.9.0' // Retrofit的SimpleXML转换器 implementation 'com.squareup.retrofit2:converter-simplexml:2.9.0' // SimpleXML核心解析库 implementation 'org.simpleframework:simple-xml:2.7.1'
第二步:创建对应XML结构的数据类
根据你提供的XML结构,需要两个数据类分别映射根节点<texts>和子节点<text>,通过SimpleXML注解完成节点与字段的绑定:
根节点数据类 Texts
import org.simpleframework.xml.ElementList import org.simpleframework.xml.Root @Root(name = "texts", strict = false) data class Texts( // inline=true 表示<text>节点直接嵌套在<texts>下,无需额外外层标签 @ElementList(name = "text", inline = true, required = false) val textList: List<Text>? = emptyList() )
子节点数据类 Text
import org.simpleframework.xml.Attribute import org.simpleframework.xml.Element import org.simpleframework.xml.Root @Root(name = "text", strict = false) data class Text( // 映射<text>节点的id属性 @Attribute(name = "id", required = false) val id: String? = null, // 映射<title>子节点 @Element(name = "title", required = false) val title: String? = null, @Element(name = "creation", required = false) val creation: String? = null, @Element(name = "valid_from", required = false) val validFrom: String? = null, @Element(name = "valid_to", required = false) val validTo: String? = null, @Element(name = "content", required = false) val content: String? = null )
第三步:配置Retrofit接口与实例
定义Retrofit请求接口,并初始化Retrofit实例:
API接口定义
import retrofit2.Call import retrofit2.http.GET interface WeatherTextApi { // 替换为实际的接口路径 @GET("your-api-endpoint") fun getWeatherTexts(): Call<Texts> }
Retrofit实例初始化
import retrofit2.Retrofit import retrofit2.converter.simplexml.SimpleXmlConverterFactory // 替换为你的API基础地址 val retrofit = Retrofit.Builder() .baseUrl("https://your-base-url.com/") .addConverterFactory(SimpleXmlConverterFactory.create()) .build() val weatherTextApi = retrofit.create(WeatherTextApi::class.java)
关键说明
strict = false:关闭严格模式,避免XML中出现未定义字段时解析失败required = false:标记字段为非必填,适配可能缺失的节点/属性inline = true:处理下直接嵌套多个节点的结构,无需额外包裹标签
内容的提问来源于stack exchange,提问作者sigjak
相关产品推荐
相关产品推荐

