Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

android - How to use Retrofit and SimpleXML together in downloading and parsing an XML file from a site?

I just started working with Retrofit. I am working on a project that uses SimpleXML. Can somebody provide me an example in which one fetches an XML from a site e.g. http://www.w3schools.com/xml/simple.xml" and reads it out?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You will create an interface as a new class in your project:

public interface ApiService {
    @GET("/xml/simple.xml")
    YourObject getUser();
}

Then in your activity you will call the following:

RestAdapter restAdapter = new RestAdapter.Builder()
                    .setEndpoint("http://www.w3schools.com")
                    .setConverter(new SimpleXmlConverter())
                    .build();

ApiService apiService = restAdapter.create(ApiService.class);
YourObject object = apiService.getXML();

To get your libraries correctly, in your build.gradle file you need to do the following:

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'
}

Then you need to specify YourObject and add annotations to it according to the structure of the xml file

@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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...