我刚刚开始使用Retrofit。我正在使用SimpleXML的项目中。有人可以给我提供一个例子吗,其中有人从某个网站获取XML。 http://www.w3schools.com/xml/simple.xml“并读出来吗?
最佳答案
您将在项目中创建一个作为新类的接口(interface):
public interface ApiService {
@GET("/xml/simple.xml")
YourObject getUser();
}
然后在您的 Activity 中,您将调用以下内容:
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("http://www.w3schools.com")
.setConverter(new SimpleXmlConverter())
.build();
ApiService apiService = restAdapter.create(ApiService.class);
YourObject object = apiService.getXML();
为了正确获取库,需要在build.gradle文件中执行以下操作:
configurations {
compile.exclude group: 'stax'
compile.exclude group: 'xpp3'
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.squareup.retrofit:retrofit:1.6.1'
compile 'com.mobprofs:retrofit-simplexmlconverter:1.1'
compile 'org.simpleframework:simple-xml:2.7.1'
compile 'com.google.code.gson:gson:2.2.4'
}
然后,您需要指定YourObject并根据xml文件的结构向其添加注释
@Root(name = "breakfast_menu")
public class BreakFastMenu {
@ElementList(inline = true)
List<Food> foodList;
}
@Root(name="food")
public class Food {
@Element(name = "name")
String name;
@Element(name = "price")
String price;
@Element(name = "description")
String description;
@Element(name = "calories")
String calories;
}