在android中读取从XML格式的服务器获取的字符串

时间:2011-11-25 07:34:19

标签: java javascript android android-widget

我正在获取PHP文件的URL,我从中获取XML格式的所有数据。 现在我能够使用InputStream读取所有这些数据并传递给buffer.But问题是我没有得到如何从可用数据中分离所有必需的数据。我尝试使用DOM,但它在我的日志中给了我以下错误

`Error in http connection java.net.MalformedURLException: Protocol not found in android

我使用的代码如下。

try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new
                        HttpPost("http://www.mbusiness.com/mobile.php?id="+id.trim());
                HttpResponse response;
                response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                InputStream is = entity.getContent();
                data = new byte[256];
                buffer = new StringBuffer();
                int len = 0;
                while (-1 != (len = is.read(data)) )
                  {
                     buffer.append(new String(data, 0, len));
                  }
                Log.e("log_tag",""+buffer.toString());

                 //Make the comparison case-insensitive.
                is.close();

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(buffer.toString());
        doc.getDocumentElement().normalize();
        Log.e("Log.Tag",""+doc);

            }
            catch(Exception e){
                Log.e("log_tag", "Error in http connection "+e.toString());
                } 

我正在阅读的PHP文件正在向我提供以下详细信息

   <profile>
    <details user_login="chirag" 
user_nickname="chirag" 
user_email="dipendra@bcod.co.in" 
display_name="chirag" 
first_name="chirag singh" 
last_name="test singh" 
nickname="chirag singh" 
description="" 
twitter_id="" 
facebook_id="" 
paypal_email="" 
business_name="My Business Test" 
business_abn="testabn" 
business_contact="Chirag Test" 
business_phone="123456789" 
business_fax="123456" 
business_mobile="1456789" 
business_emailss="chirag@gmail.com" 
business_facebookzz="http://www.facebook.com" 
business_linkedin="http://www.linkedin.com" 
business_myspace="http://myspacelink.com" 
business_blog="Blog" 
business_im="im" 
business_website="tester" 
business_street="TestStreet" 
business_city="TestCity" 
business_postcode="123456" 
business_state="NSW New South Wales" 
business_trading="12345" 
business_area="500" 
business_trade="Saturday" 
business_products="TesterProducts" 
business_services="testerservices" 
business_delivery="only sunday" 
redirect_to=""/>
    </profile>

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

DocumentBuilder的parse(String)方法期望将URL作为参数,而不是XML内容作为String。您可以直接将InputStream传递给parse方法而不需要任何缓冲来简化代码:

InputStream is = entity.getContent();

try {
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(is);
} finally {
    is.close();
}