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

如何使用Retrofit解析Simple XML格式?请生成对应XML响应实体类

没问题,我来一步步教你用Retrofit解析这个Simple XML响应,顺便帮你把对应的实体类写好~

使用Retrofit解析Simple XML格式的完整步骤

1. 先添加必要的依赖

在你的App模块的build.gradle(或build.gradle.kts)中,加入Retrofit核心库和Simple XML转换器的依赖:

// Retrofit核心库
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
// Simple XML转换器,用于XML解析
implementation 'com.squareup.retrofit2:converter-simplexml:2.9.0'
// Simple XML核心解析库
implementation 'org.simpleframework:simple-xml:2.7.1'

2. 创建对应XML的实体类

根据你提供的XML结构,我们需要一个根实体类来映射整个XML内容,注意标签名要和XML完全匹配(XML大小写敏感):

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

@Root(name = "idxml", strict = false)
// strict=false:允许忽略XML中未在实体类定义的标签(如果后续有新增标签也不会报错)
public class IdXmlResponse {

    @Element(name = "Status", required = true)
    private String status;

    @Element(name = "Msisdn", required = false)
    // required=false:该标签可能为空,避免解析时抛出异常
    private String msisdn;

    @Element(name = "OperatorCode", required = false)
    private String operatorCode;

    @Element(name = "OrderId", required = false)
    private String orderId;

    @Element(name = "Details", required = true)
    private String details;

    @Element(name = "Signature", required = false)
    private String signature;

    // 生成getter和setter方法,方便获取数据
    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getMsisdn() {
        return msisdn;
    }

    public void setMsisdn(String msisdn) {
        this.msisdn = msisdn;
    }

    public String getOperatorCode() {
        return operatorCode;
    }

    public void setOperatorCode(String operatorCode) {
        this.operatorCode = operatorCode;
    }

    public String getOrderId() {
        return orderId;
    }

    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }

    public String getDetails() {
        return details;
    }

    public void setDetails(String details) {
        this.details = details;
    }

    public String getSignature() {
        return signature;
    }

    public void setSignature(String signature) {
        this.signature = signature;
    }
}

3. 配置Retrofit实例

关键是要添加SimpleXmlConverterFactory作为XML解析转换器:

import retrofit2.Retrofit;
import retrofit2.converter.simplexml.SimpleXmlConverterFactory;

public class RetrofitClient {
    private static Retrofit retrofit;
    private static final String BASE_URL = "你的API基础地址"; // 替换成实际的接口地址

    public static Retrofit getRetrofitInstance() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(SimpleXmlConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

4. 创建API接口定义

根据你的请求类型(GET/POST等),定义对应的接口方法:

import retrofit2.Call;
import retrofit2.http.GET; // 如果是POST请求就用@POST,路径替换成实际接口路径

public interface ApiService {
    @GET("your-api-endpoint")
    Call<IdXmlResponse> getIdXmlResponse();
}

5. 调用API并解析响应

最后是实际发起请求并处理解析结果的示例:

ApiService apiService = RetrofitClient.getRetrofitInstance().create(ApiService.class);
Call<IdXmlResponse> call = apiService.getIdXmlResponse();

call.enqueue(new retrofit2.Callback<IdXmlResponse>() {
    @Override
    public void onResponse(Call<IdXmlResponse> call, retrofit2.Response<IdXmlResponse> response) {
        if (response.isSuccessful() && response.body() != null) {
            IdXmlResponse responseData = response.body();
            // 这里可以获取解析后的数据
            String status = responseData.getStatus();
            String errorDetails = responseData.getDetails();
            // 处理你的业务逻辑
        } else {
            // 处理请求失败的情况
        }
    }

    @Override
    public void onFailure(Call<IdXmlResponse> call, Throwable t) {
        // 处理网络错误等异常
        t.printStackTrace();
    }
});

小提示

  • 如果你的XML带有命名空间,需要在@Root和@Element注解中添加namespace="你的命名空间"参数
  • 所有可能为空的标签一定要设置required=false,否则解析时会抛出异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:14:33