使用 Retrofit 2 讀取 XML 表單 URL

我們將使用 retrofit 2 和 SimpleXmlConverter 從 url 獲取 xml 資料並解析為 Java 類。

向 Gradle 指令碼新增依賴項:

compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-simplexml:2.1.0'

建立介面

在我們的 Rss 類中建立 xml 類包裝器

    public interface ApiDataInterface{
    
        // path to xml link on web site
    
        @GET (data/read.xml)
    
        Call<Rss> getData();

}

Xml 讀取功能

private void readXmlFeed() {
        try {

            // base url - url of web site
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(http://www.google.com/)
                    .client(new OkHttpClient())
                    .addConverterFactory(SimpleXmlConverterFactory.create())
                    .build();

            ApiDataInterface apiService = retrofit.create(ApiDataInterface.class);

            Call<Rss> call = apiService.getData();
            call.enqueue(new Callback<Rss>() {

                @Override
                public void onResponse(Call<Rss> call, Response<Rss> response) {

                    Log.e("Response success", response.message());
                    
                }

                @Override
                public void onFailure(Call<Rss> call, Throwable t) {
                    Log.e("Response fail", t.getMessage());
                }
            });

        } catch (Exception e) {
            Log.e("Exception", e.getMessage());
        }

    }

這是帶有 SimpleXML 註釋的 Java 類的示例

有關注釋 SimpleXmlDocumentation 的更多資訊

@Root (name = "rss")

public class Rss
{

    public Rss() {

    }

    public Rss(String title, String description, String link, List<Item> item, String language) {

        this.title = title;
        this.description = description;
        this.link = link;
        this.item = item;
        this.language = language;

    }

    @Element (name = "title")
    private String title;

    @Element(name = "description")
    private String description;

    @Element(name = "link")
    private String link;

    @ElementList (entry="item", inline=true)
    private List<Item> item;

    @Element(name = "language")
    private String language;