2013-03-21 45 views
0

我是android编程的新手。我的需求是调用web服务。我成功地从web services中得到了响应。在android.Give中我解析了响应。如何在android中解析xml数据的字符串

这是获得响应代码:

HttpResponse response = httpclient.execute(httppost); 
      String str=response.getStatusLine().toString(); 

      System.out.println("========URL STATUS========"+str); 

      HttpEntity r_entity = response.getEntity(); 

      if(r_entity != null) { 
       result = new byte[(int) r_entity.getContentLength()]; 
       if(r_entity.isStreaming()) { 
        is = new DataInputStream(r_entity.getContent()); 
        is.readFully(result); 

       } 
      } 

      httpclient.getConnectionManager().shutdown(); 
      String responsedata= (new String(result).toString()); 
+0

什么类型的格式,你会得到回应? – rajeshwaran 2013-03-21 12:38:11

+0

首先看看EntityUtils.toString(),其次是:使用像SimpleXML或其他东西一样的XML解析器 – 2013-03-21 12:39:31

回答

3

以下示例适用于dom解析器。

DocumentBuilderFactory dbf =DocumentBuilderFactory.newInstance(); 
DocumentBuilder db = dbf.newDocumentBuilder(); 
InputSource is = new InputSource(); 
StringReader sr=new StringReader(result.toString()); 
is.setCharacterStream(sr); 
Document doc = db.parse(is); 
NodeList nodes = doc.getElementsByTagName("your root tag"); 

//get your other tag elements. 

http://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/。 dom解析器的例子。

http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/。萨克斯分析器的例子。

Dom是基于w3c的解析器。 Dom比sax慢,因为它使用树节点并且必须位于mmeory中。因此不建议使用DOM解析器解析大数据。

SAX另一方面比dom更快。推荐用于大型XML数据。

上面的链接给你两个例子。使用上述任何解析器来解析和获取xml标签中的值。

+0

我解析结果,但它是给整个结果作为一个string.how以XML标记明智分裂? – user2195073 2013-03-21 13:12:56

+0

你必须使用sax或dom解析器或简单的xml解析器来解析xml – Raghunandan 2013-03-21 13:21:20

0

你可以尝试使用SimpleXmlParser。这是一个原生的android类。它比DOM xml解析器更简单。