简体   繁体   中英

Convert custom model to XML string with SimpleXmlConverter or by any other library?

I'm working with Retrofit2 and SimpleXmlConverter to call the APIs. The request and response is based on the XML data. I need to send XML string with tags in the request body.

By using SimpleXmlConverter, I can easily parse XML response into my custom models but I can't able to convert my custom model into XML string like we do with JsonConverters.

Is there any way to convert my custom model into XML string?

By using Serializer class of SimpleXmlConverter library you can do the parsing. Refer below code:

This is the custom model class

import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

@Root(name = "notification", strict = false)
public class NotificationModel {

    @Element(name = "code")
    public String errorCode;

    @Element(name = "message")
    public String errorMessage;
}

This is the xml string which you want to parse into the model

<notification xmlns:d="http://www.website.com/pref/data">
    <code>004</code>
    <message>Error during value update</message>
    <severity>info</severity>
    <target />
</notification>

Use the below code to parse the above xml string

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

String xmlString = "above xml string"
try {
    Serializer serializer = new Persister();
    NotificationModel notificationModel = serializer.read(NotificationModel.class, xmlString);
    //TODO: Use notificationModel's variables with filled values
} catch (Exception e) {
    e.printStackTrace();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM