2012-02-13 57 views
0

我正在开发一个android应用程序,我必须从.Net webservice获取数据最初webservice的方法返回简单的字符串。这很好,我的代码工作正常,顺利地获取字符串。但是我的问题在方法返回对象时开始,我知道对象以XML形式保存数据。我也通过调试我的代码来确认它,结果对象保存下面给出的数据。在android中查询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>[email protected]</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 data.Now我的问题是,当我使用的代码打印对象的数据tv4.setText(""+results);它给我class java.lang.ClassCastException。我知道这是不正确的方法来获取对象的XML数据,我不得不解析它。但我不知道如何解析对象。所以请帮助我解析XML包含object.Any帮助将高度赞赏。提前告知。

回答

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(); 

}} 

如下retrived soapobject设置为实体类的方式。

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

如果您需要更多说明,请与我联系... – Rakhita 2012-02-13 06:52:02