036 036 036

Retrofit2+SimpleXML Kotlin how to parse XML

508 Views Asked by At

How to create data class for this info:

<ValCurs Date="09.02.2022" name="Foreign Currency Market">
 <Valute ID="R01010">
  <NumCode>036</NumCode>
  <CharCode>AUD</CharCode>
  <Nominal>1</Nominal>
  <Name>Australian dollar</Name>
  <Value>53,6768</Value>
 </Valute>
 <Valute ID="R01020A">
  <NumCode>944</NumCode>
  <CharCode>RUB</CharCode>
  <Nominal>1</Nominal>
  <Name>Russian ruble</Name>
  <Value>44,3227</Value>
 </Valute>
...More info like that...
</ValCurs>

And how to get this info from response?

1

There are 1 best solutions below

0
simon5678 On

Sample code:

xml:

<my-object>
    <message>hello world</message>
    <count>10</count>
</my-object>

import org.simpleframework.xml.Default;
import org.simpleframework.xml.DefaultType;
import org.simpleframework.xml.Element;

@Default(value = DefaultType.FIELD)
final class MyObject {
  @Element private String message;
  @Element private int count;

  public MyObject() {}

  public MyObject(String message, int count) {
    this.message = message;
    this.count = count;
  }

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

  public String getMessage() {
    return message;
  }

  public void setCount(int count) {
    this.count = count;
  }

  public int getCount() {
    return count;
  }
}
    Format format = new Format(0, null, new HyphenStyle(), Verbosity.HIGH);
    Persister persister = new Persister(format);
    Retrofit retrofit =
        new Retrofit.Builder()
            .baseUrl(server.url("/"))
            .addConverterFactory(SimpleXmlConverterFactory.create(persister))
            .build();
    service = retrofit.create(Service.class);

  interface Service {
    @GET("/")
    Call<MyObject> get();

    @POST("/")
    Call<MyObject> post(@Body MyObject impl);

    @GET("/")
    Call<String> wrongClass();
  }

Link: https://github.com/square/retrofit/blob/master/retrofit-converters/simplexml/src/test/java/retrofit2/converter/simplexml/SimpleXmlConverterFactoryTest.java