2013-03-19 84 views
0

目前我正在使用Android中的XML解析。我不知道它是如何工作的。我使用下面的代碼:如何在Android中實現XML解析?

HttpClient httpClient = new DefaultHttpClient(); 
HttpPost postRequest = new HttpPost(MobileServiceConst.URL); 
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE); 
reqEntity.addPart("method", new StringBody(MobileServiceConst.UPLOAD_CONTACTS)); 
reqEntity.addPart("user_id", new StringBody(String.valueOf(Constants.userData.getUserInfo().getuserId()))); 
reqEntity.addPart("accesstoken", new StringBody(Constants.userData.getMYToken())); 
reqEntity.addPart("data",new StringBody(jsnConts.toString())); 
reqEntity.addPart("device_id",new StringBody(regId)); 
postRequest.setEntity(reqEntity); 


HttpResponse response = httpClient.execute(postRequest); 
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); 



StringBuilder s = new StringBuilder(); 

    while ((sResponse = reader.readLine()) != null) { 

      s = s.append(sResponse); 

    } 

sResponse = s.toString(); 

System.out.println("responseeeeeeeeeeeeeee"+sResponse); 

sResponse是按以下格式:

<CS_Mservice_Main generator="check" version="1.0"> 
<getContacts> 
<mycnt> 
<key_0> 
<id>1</id> 
<user_id>22434</user_id> 
<device_id>121212,</device_id> 
<contact_id></contact_id> 
<firstname></firstname> 
<lastname></lastname> 
<email></email> 
<email1></email1> 
<email2></email2> 
<contact1>9809788201</contact1> 
<contact2></contact2> 
<contact3></contact3> 
<contact4></contact4> 
<created_at>2013-03-18 13:29:12</created_at> 
</key_0> 
<key_1> 
<id>16</id> 
<user_id>17025</user_id> 
<device_id>APA91bGRyoeOlxZjhfjkdshjsdfsdsdf9kICZFsveU_QonqbNIbYONWLtiHpT4CmPe1aJg3rZ86noqj2HKshgZRlk1dc0Em7AVte2usHaP-qRzVBcP8BWzJuXa8ozA</device_id> 
<contact_id></contact_id> 
<firstname>Rahul</firstname> 
<lastname>Jain</lastname> 
<email>[email protected]</email> 
<email1></email1> 
<email2></email2> 
<contact1></contact1> 
<contact2></contact2> 
<contact3></contact3> 
<contact4></contact4> 
<created_at>2013-03-18 13:30:04</created_at> 
</key_1> 
</mycnt> 
<email/> 
<sms/> 
<status>success</status> 
</getContacts> 
</CS_Mservice_Main> 

如何可以解析這種格式?

+1

有什麼理由http://developer.android.com/reference/org/xmlpull/v1/XmlPullParser.html 不會工作? – Arveen 2013-03-19 04:30:11

+0

哪個標籤可以解析並顯示在手機中? – 2013-03-19 04:31:30

+0

我需要解析所有細節並將其存儲在單獨的數組列表中 – jithu 2013-03-19 04:33:54

回答

1
import java.io.IOException; 
import java.io.StringReader; 

import org.xmlpull.v1.XmlPullParser; 
import org.xmlpull.v1.XmlPullParserException; 
import org.xmlpull.v1.XmlPullParserFactory; 

public class SimpleXmlPullApp 
{ 

    public static void main (String args[]) 
     throws XmlPullParserException, IOException 
    { 
     XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); 
     factory.setNamespaceAware(true); 
     XmlPullParser xpp = factory.newPullParser(); 

     xpp.setInput(new StringReader ("<foo>Hello World!</foo>")); 
     int eventType = xpp.getEventType(); 
     while (eventType != XmlPullParser.END_DOCUMENT) { 
      if(eventType == XmlPullParser.START_DOCUMENT) { 
       System.out.println("Start document"); 
      } else if(eventType == XmlPullParser.START_TAG) { 
       System.out.println("Start tag "+xpp.getName()); 
      } else if(eventType == XmlPullParser.END_TAG) { 
       System.out.println("End tag "+xpp.getName()); 
      } else if(eventType == XmlPullParser.TEXT) { 
       System.out.println("Text "+xpp.getText()); 
      } 
      eventType = xpp.next(); 
     } 
     System.out.println("End document"); 
    } 
} 

試試這個在android.for XML解析更多檢查鏈接

http://developer.android.com/reference/org/xmlpull/v1/XmlPullParser.html

0

解析XML內容並獲取Dom元素。

public Document getDomElement(String xml){ 
     Document doc = null; 
     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
     try { 

      DocumentBuilder db = dbf.newDocumentBuilder(); 

      InputSource is = new InputSource(); 
       is.setCharacterStream(new StringReader(xml)); 
       doc = db.parse(is); 

      } catch (ParserConfigurationException e) { 
       Log.e("Error: ", e.getMessage()); 
       return null; 
      } catch (SAXException e) { 
       Log.e("Error: ", e.getMessage()); 
       return null; 
      } catch (IOException e) { 
       Log.e("Error: ", e.getMessage()); 
       return null; 
      } 
       // return DOM 
      return doc; 
    } 
+0

03-19 10:16:18.425:I/System.out(10063):Doccccccc[email protected]42381c78,我得到了文檔,然後下一個階段我想要做? – jithu 2013-03-19 04:46:42

1

定義一個新的分析器類像這樣和實現這個類在任何你需要的XML解析 公共XMLParser類{

public String getXmlFromUrl(String url) { 
    String xml = null; 

    try { 
     DefaultHttpClient httpClient = new DefaultHttpClient(); 
     HttpPost httpPost = new HttpPost(url); 

     HttpResponse httpResponse = httpClient.execute(httpPost); 
     HttpEntity httpEntity = httpResponse.getEntity(); 
     xml = EntityUtils.toString(httpEntity); 

    } catch (UnsupportedEncodingException e) { 
     e.printStackTrace(); 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    return xml; 
} 

public Document getDomElement(String xml){ 
    Document doc = null; 
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
    try { 

     DocumentBuilder db = dbf.newDocumentBuilder(); 

     InputSource is = new InputSource(); 
     is.setCharacterStream(new StringReader(xml)); 
     doc = db.parse(is); 

    } catch (ParserConfigurationException e) { 
     Log.e("Error: ", e.getMessage()); 
     return null; 
    } catch (SAXException e) { 
     Log.e("Error: ", e.getMessage()); 
     return null; 
    } catch (IOException e) { 
     Log.e("Error: ", e.getMessage()); 
     return null; 
    } 

    return doc; 
} 

public String getValue(Element item, String str) { 
    NodeList n = item.getElementsByTagName(str); 
    return this.getElementValue(n.item(0)); 
} 

public final String getElementValue(Node elem) { 
    Node child; 
    if(elem != null){ 
     if (elem.hasChildNodes()){ 
      for(child = elem.getFirstChild(); child != null; child = child.getNextSibling()){ 
       if(child.getNodeType() == Node.TEXT_NODE ){ 
        return child.getNodeValue(); 
       } 
      } 
     } 
    } 
    return ""; 
} 

} 

現在你需要調用這個解析類,它會接受網址爲輸入並返回文檔對象

如果XML資源是靜態的,則必須將XMl置於Res文件夾中,否則您可以遵循此結構

讓XMLParser的類的對象,這樣的

parser = new XMLParser(); 
xml = parser.getXmlFromUrl(URL); 
doc = parser.getDomElement(xml); 

不是採取一個HashMap和存儲來自各標籤輸出

NodeList nl = doc.getElementsByTagName(KEY_ITEM); 
     // looping through all item nodes <item> 
     for (int i = 0; i < nl.getLength(); i++) { 
      // creating new HashMap 
      HashMap<String, String> map = new HashMap<String, String>(); 
      Element e = (Element) nl.item(i); 
      // adding each child node to HashMap key => value 

      map.put(KEY_ID, "ID id:" +parser.getValue(e, KEY_ID)); 
      map.put(KEY_NAME, "Name" + parser.getValue(e, KEY_NAME)); 
      map.put(KEY_COST, "Rs." + parser.getValue(e, KEY_COST)); 
      map.put(KEY_DESC, "Desc: "+ parser.getValue(e, KEY_DESC)); 



      // adding HashList to ArrayList 
      menuItems.add(map); 

     } 
     getXML(); 

您還可以幫助從本教程Source