美文网首页
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数据并解析

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