美文网首页
Retrofit请求xml数据并解析

Retrofit请求xml数据并解析

作者: 霁逸lei | 来源:发表于2018-07-19 20:52 被阅读0次

我也喜欢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

<?xml version='1.0' encoding='ISO-8859-1'?>
<note>
  <from>John</from>
  <to>George</to>
  <message>Don't forget the meeting!</message>
</note>

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<Note> getNoteMsg();

    @GET("note.asp")
    Call<Note> 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<Note> call = xmlService.getNote();
//        call.enqueue(new Callback<Note>() {
//            @Override
//            public void onResponse(Call<Note> call, Response<Note> response) {
//                Log.d("XmlActivity", response.body().toString());
//            }
//
//            @Override
//            public void onFailure(Call<Note> call, Throwable t) {
//                Log.d("XmlActivity", t.toString());
//            }
//        });
        xmlService.getNoteMsg()
                .subscribeOn(Schedulers.io())
                .subscribe(new Consumer<Note>() {
                    @Override
                    public void accept(Note note) throws Exception {
                        Log.d("XmlActivity", note.toString());
                    }
                }, new Consumer<Throwable>() {
                    @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
<?xml version="1.0" encoding="ISO-8859-1"?>
<CATALOG>
  <CD>
    <TITLE>Hide your heart</TITLE>
    <ARTIST>Bonnie Tyler</ARTIST>
    <COUNTRY>UK</COUNTRY>
    <COMPANY>CBS Records</COMPANY>
    <PRICE>9.90</PRICE>
    <YEAR>1988</YEAR>
  </CD>
  <CD>
      ...
  </CD>
</CATALOG>

对应javabean

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

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

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

    public void setCdList(List<Cd> 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数据并解析

    我也喜欢json然并卵服务器给xml,胳膊拧不过大腿...1.配置xml解析器 2.网上搜一个xml文件http:...

  • 五、Groovy语法(五)json、xml解析

    Groovy数据解析 一、json解析 请求网络数据并解析 二、xml解析 groovy解析xml数据 groov...

  • 10 android网络编程

    HTTP请求方式:HttpURLConnection XML数据解析 JSON数据解析 文件上传 文件下载 调用 ...

  • Retrofit 工作原理总结

    Retrofit源码解析之请求流程概述Retrofit之Converter简单解析Retrofit之OkhttpC...

  • js解析xml

    案例:ajax请求获取的数据为xml文件,解析xml标签中的数据信息 1、ajax请求,测试地址为:获取地图坐标偏...

  • AFN如何获取并解析XML

    开发中如果通过网络请求,接收服务器返回的是XML数据,需要将XML数据解析。 首先AFN需要加载一下XML解析器,...

  • Android面试宝典~性能优化

    响应时间优化 1、网络请求 使用优秀的网络框架库来提高请求速度 比如retrofit、okhttp 2、数据解析 ...

  • Retrofit2.1源码解析

    Retrofit2.1源码解析 标签(空格分隔): java android 网络请求 retrofit OkHt...

  • retrofit源码解析(三)

    之前描述了retrofit的实例 retrofit源码解析(一)实例化 以及retrofit的网络请求 retro...

  • XML数据解析

    当请求到数据之后 // 1.根据需要解析的XML数据, 创建NSXMLParser对象 NSXMLPars...

网友评论

      本文标题:Retrofit请求xml数据并解析

      本文链接:https://www.haomeiwen.com/subject/oalxmftx.html