Retrofit请求xml数据并解析

我也喜欢json然并卵服务器给xml,胳膊拧不过大腿...
1.配置xml解析器

compile ('com.squareup.retrofit2:converter-simplexml:2.3.0') {
        exclude group: 'xpp3', module: 'xpp3'
        exclude group: 'stax', module: 'stax-api'
        exclude group: 'stax', module: 'stax' }

2.网上搜一个xml文件http://www.w3school.com.cn/xml/note.asp



  John
  George
  Don't forget the meeting!

3.写xml对应的javabean

**注意一定要写空构造,或者你就不写构造函数让他默认空构造,否则
XmlActivity: throwable:java.lang.RuntimeException: org.simpleframework.xml.core.PersistenceException: Constructor not matched for class com.lei.simpletest.retrofit.bean.Note

// @Root(strict = false) @注解(不严格检查)
@Root(name = "note",strict = false)
public class Note {
    @Element(name = "from")
    private String from;
    @Element(name = "to")
    private String to;
    @Element(name = "message")
    private String message;

    public Note() {
    }

    public Note(String from, String to, String message) {
        this.from = from;
        this.to = to;
        this.message = message;
    }

    public String getFrom() {
        return from == null ? "" : from;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public String getTo() {
        return to == null ? "" : to;
    }

    public void setTo(String to) {
        this.to = to;
    }

    public String getMessage() {
        return message == null ? "" : message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    @Override
    public String toString() {
        return "Note{" +
                "from='" + from + '\'' +
                ", to='" + to + '\'' +
                ", message='" + message + '\'' +
                '}';
    }
}

4.开干 XmlService

public interface XmlService {
    @GET("note.asp")
    Observable getNoteMsg();

    @GET("note.asp")
    Call getNote();
}

5.XmlActivity

public class XmlActivity extends Activity {

    public static final String BaseUrl = "http://www.w3school.com.cn/xml/";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView content = findViewById(R.id.tv);
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BaseUrl)
                .addConverterFactory(SimpleXmlConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        XmlService xmlService = retrofit.create(XmlService.class);
//        Call call = xmlService.getNote();
//        call.enqueue(new Callback() {
//            @Override
//            public void onResponse(Call call, Response response) {
//                Log.d("XmlActivity", response.body().toString());
//            }
//
//            @Override
//            public void onFailure(Call call, Throwable t) {
//                Log.d("XmlActivity", t.toString());
//            }
//        });
        xmlService.getNoteMsg()
                .subscribeOn(Schedulers.io())
                .subscribe(new Consumer() {
                    @Override
                    public void accept(Note note) throws Exception {
                        Log.d("XmlActivity", note.toString());
                    }
                }, new Consumer() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Log.d("XmlActivity", "throwable:" + throwable);
                    }
                });
    }
}

打印结果如下:
07-19 20:51:31.990 17931-17965/com.lei.simpletest.retrofit D/XmlActivity: Note{from='John', to='George', message='Don't forget the meeting!'}

大功告成,当然还有复杂的xml等我baidu完再加...

https://www.w3cschool.cn/statics/demosource/cd_catalog.xml


  
    Hide your heart
    Bonnie Tyler
    UK
    CBS Records
    9.90
    1988
  
  
      ...
  

对应javabean

inline表示是否内联,entry表示每个子元素的标签名字,required表示是否为必须标签
@Root(name = "CATALOG",strict = false)
public class Catalog {

    @ElementList(inline = true, entry = "CD", required = false)
    public List cdList;

    public List getCdList() {
        if (cdList == null) {
            return new ArrayList<>();
        }
        return cdList;
    }

    public void setCdList(List cdList) {
        this.cdList = cdList;
    }

    @Override
    public String toString() {
        return "Catalog{" +
                "cdList=" + cdList +
                '}';
    }
}

@Root(name = "CD",strict = false)
public class Cd {
    @Element(name = "TITLE")
    String title;
    @Element(name = "ARTIST")
    String artist;
    @Element(name = "COUNTRY")
    String country;
    @Element(name = "PRICE")
    String price;
    @Element(name = "YEAR")
    String year;
}

你可能感兴趣的:(Retrofit请求xml数据并解析)