Search code examples
javaandroidxmlksoap2

Get data from XML in String - Android


I'm using SOAP service to get ticket. I'm sending user and pass, and I'm getting xml in String. For this I'm using ksoap2.

@Override
protected String doInBackground(String... params) {

    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
    request.addProperty(USER, params[0]);
    request.addProperty(PASS, params[1]);

    SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    soapEnvelope.bodyOut = request;
    soapEnvelope.setOutputSoapObject(request);

    HttpTransportSE HttpTransport = new HttpTransportSE(URL);
    try {
        HttpTransport.call(SOAP_ACTION, soapEnvelope);
        return soapEnvelope.getResponse().toString();
    } catch (IOException | XmlPullParserException e) {
        e.printStackTrace();
        return null;
    }
}

@Override
    protected void onPostExecute(String XML) {
        super.onPostExecute(XML);
        if (result != null) {
           // Here I need to get data from XML

        }
    }

My XML String looks like this:

<?xml version="1.0" encoding="UTF-8" ?>
<resp err="0">
<ticket>1234567989</ticket>
</resp>

So I need to get the error number, and the ticket number.


Solution

  • Don't convert your response to String and return it, instead get properties you need with getProperty() method and convert them to String. Here's how i was doing it:

        String ticket;
    
        public void getSoap() {
    
        SoapObject request = new SoapObject(NAMESPACE, METHODNAME);
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.implicitTypes = false;
        envelope.setOutputSoapObject(request);
        HttpTransportSE httpTransportSe = new HttpTransportSE(URL);
        httpTransportSe.debug = true;
        SoapObject response = null;
    
        try {
            httpTransportSe.call(SOAPACTION, envelope);
            response = (SoapObject) envelope.getResponse();
            ticket = response.getProperty("ticket").toString();
    
        } catch (Exception e) {
            e.printStackTrace();
        }
    
    }
    

    Getting "err" element from attribute might require a bit more research but you can try this where you get ticket:

    String err = response.getAttribute("err").toString;
    

    Hope this helps and happy coding !