查询android中的xml解析

时间:2012-02-13 06:24:37

标签: android web-services xml-parsing

我正在开发一个Android应用程序,其中我必须从.Net webservice获取数据最初的webservice方法返回简单的字符串。这很好我的代码工作正常并且顺利地获取字符串。但是我的问题开始了当方法返回对象时,我知道对象以XML格式保存数据。我也通过调试我的代码来确认它,结果对象保存下面给出的数据。

<?xml version="1.0" encoding="utf-8"?>

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

<soap:Body>

<UserInfoResponse xmlns="http://tempuri.org/">

<UserInfoResult>

<UserName>Himanshu</UserName>

<Email>Himanshu@XXXXXXXX.com</Email>

</UserInfoResult>

</UserInfoResponse>

</soap:Body>

</soap:Envelope>

我使用Web服务的代码是: -

public void objData(){

        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME2);
        Log.d("request", request.toString());

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        Log.d("envelope", envelope.toString());

        envelope.dotNet = true;
        envelope.setOutputSoapObject(request);
        Log.d("envelope", envelope.toString());

        HttpTransportSE aht = new HttpTransportSE(URL);
        aht.debug=true;
        Log.d("aht", aht.toString());

        try
        {
            aht.call(OBJ_SOAP_ACTION, envelope);
            SoapPrimitive results = (SoapPrimitive)envelope.getResponse();
            System.out.println("results="+results);
            tv4.setText(""+results);
        }
        catch (Exception e)
        {
            tv4.setText(e.getClass().toString());
            Log.d("Error",e.getClass().toString());
        }

    }

对象results包含xml数据。现在我的问题是当我使用代码tv4.setText(""+results);打印该对象的数据时它会给我class java.lang.ClassCastException。我知道这个获取对象的xml数据不是正确的方法,我必须解析它。但我不知道如何解析object.So请帮我解析xml包含的对象。任何帮助都将受到高度赞赏。提前提示。

2 个答案:

答案 0 :(得分:2)

你不能将SoapPrimitive用于复杂对象,你必须像下面那样强制转换

SoapObject response = (SoapObject) envelope.getResponse();

然后,如果你想将它转换为实体对象(类似于你通过.net web服务发送的对象),你必须这样做。

实体类

public class EmLogin {

private String _id;

private String _pwd;


public EmLogin() {
}

public String getId() {
    return _id;
}

public void setId(String id) {
    this._id = id;
}

public String getPwd() {
    return _pwd;
}

public void setPwd(String pwd) {
    this._pwd = pwd;
}

//this is the place you are setting the SoapObject as a param
public EmLogin(SoapObject so) throws ParseException {

    this._id = so.getProperty("Id").toString();// these are the properties of your xml objs
    this._pwd = so.getProperty("PasswordHash").toString();

}}

将已恢复的soapobject设置为实体类的方法如下。

EmLogin = null;
if (yourSoapObject!= null) {
    // here you are parsing the soapobject to the emlogin object as a param
    emLogin = new EmLogin(yourSoapObject);
}

答案 1 :(得分:0)

要从soap获取复杂数据对象,请通过实现KvmSerializable将对象定义为KvmSerializale,请参阅link:

http://seesharpgears.blogspot.in/2010/10/ksoap-android-web-service-tutorial-with.html

http://seesharpgears.blogspot.in/2010/11/implementing-ksoap-marshal-interface.html