如何从Android中的HttpResponse解析这个特定的XML?

时间:2013-06-20 16:33:54

标签: android xml httpresponse

我是Android开发的新手。我制作了一个Android应用程序,用于登录网站。登录页面有三个输入'用户名','密码'和& '销'。 我已经使用HttpPost方法成功传递了这些数据。见代码,

HttpClient httpclient = new DefaultHttpClient();

HttpPost httppost = new HttpPost("http://www.mysite.com/api/service.php");

try {
    // Add user name, password & pin
    String action = "login";

    EditText uname = (EditText)findViewById(R.id.txt_username);
    String username = uname.getText().toString();

    EditText pword = (EditText)findViewById(R.id.txt_password);
    String password = pword.getText().toString();

    EditText pcode = (EditText) findViewById (R.id.txt_pin);
    String pin = pcode.getText().toString();

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
    nameValuePairs.add(new BasicNameValuePair("action", action));
    nameValuePairs.add(new BasicNameValuePair("username", username));
    nameValuePairs.add(new BasicNameValuePair("password", password));
    nameValuePairs.add(new BasicNameValuePair("pin", pin));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    // Execute HTTP Post Request
    Log.w("PS", "Execute HTTP Post Request");
    HttpResponse response = httpclient.execute(httppost);

    } catch (ClientProtocolException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
   }

现在我要解析'ack'&amp;来自HttpResponse的'msg'是在将数据传递到网站后出现的XML输出。见这里,

<login>
<member>
<id/>
<username/>
<name/>
<ewallpoints/>
<ack>FAILED</ack>
<msg>Wrong Username and Password</msg>
</member>
</login>

1 个答案:

答案 0 :(得分:0)

使用response.getEntity().getContent()获取输入流并使用@tobias建议的DOM,SAX或XPath处理它。有很多选择。

您也可以直接获取xml字符串。改变行

HttpResponse response = httpclient.execute(httppost);

String xml = httpclient.execute(httppost, new BasicResponseHandler());