2011-10-08 78 views
0

我將如何返回/解析具有特定值的節點元素。Android根據日期值解析XML

下面是我簡單的XML,但我只需要timemeeting_namehost_name從具有的2012-03-09日期的meeting_item的:

<meeting_item> 
    <time>12:30</time> 
    <date>2012-03-09</date> 
    <meeting_name>build a shop 4</meeting_name> 
    <host_name>Bob Jones</host_name> 
</meeting_item> 
<meeting_item> 
    <time>11:30</time> 
    <date>2012-03-23</date> 
    <meeting_name>build a shop advance</meeting_name> 
    <host_name>Judy Washington</host_name> 
</meeting_item> 
<meeting_item> 
    <time>11:30</time> 
    <date>2012-03-23</date> 
    <meeting_name>build a shop 2</meeting_name> 
    <host_name>Tom Smith</host_name> 
</meeting_item> 
<meeting_item> 
    <time>11:30</time> 
    <date>2012-04-06</date> 
    <meeting_name>build a shop 3</meeting_name> 
    <host_name>Tom Green</host_name> 
</meeting_item> 

下面是我的解析代碼,但迄今爲止這只是得到一切都在文件中:

 String xml = XMLfunctions.getXML(items); 
     Log.d(TAG, xml); 
     Document doc = XMLfunctions.XMLfromString(xml); 
int numResults = XMLfunctions.numResults(doc); 

     if((numResults <= 0)){ 
      Toast.makeText(MeetingManager.this, "NOT GETTING XML", Toast.LENGTH_LONG).show(); 
      finish(); 
     } 

     Element docElem = doc.getDocumentElement(); 
     NodeList nl = docElem.getElementsByTagName("Meeting_Data"); 
     Element elem = (Element)nl.item(1); 
     NodeList nodes = elem.getElementsByTagName("meeting_item"); 



     for (int i = 0; i < nodes.getLength(); i++) {       
      HashMap<String, String> map = new HashMap<String, String>();  

      Element e = (Element)nodes.item(i); 
      map.put("time", XMLfunctions.getValue(e, "time")); 
      map.put("name", XMLfunctions.getValue(e, "meeting_name")); 
      map.put("hostname", XMLfunctions.getValue(e, "host_name")); 
      mylist.add(map);    
     }  

     ListAdapter adapter = new SimpleAdapter(MeetingManager.this, mylist , R.layout.listlayout, 
         new String[] {"time", "name", "hostname" }, 
         new int[] { R.id.time, R.id.meeting_name, R.id.host }); 

     setListAdapter(adapter); 

而且在我的logcat Log.d(TAG,XML);並不能完成整個文件。有時會拋出錯誤而不讀取所有文件。有沒有限制我可以httpGet?

回答

0

如果您只想解析xml文件的一部分,我建議您使用類似XmlPullParser或SaxParser的東西。由於dom解析器將嘗試根據您的xml數據創建一個完整的對象樹。要使用xml pull解析器執行此操作,您的解析代碼將看起來像

XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); 
factory.setNamespaceAware(false); 
factory.setValidating(false); 
XmlPullParser xpp = factory.newPullParser(); 
xpp.setInput(is,"UTF-8"); 

int eventType = xpp.getEventType(); 
outerloop: 
while (eventType != XmlPullParser.END_DOCUMENT) { 
    switch(eventType){ 
     case XmlPullParser.START_DOCUMENT: 
      Log.e("Start","Start"); 
      break; 
     case XmlPullParser.START_TAG: 
      Log.e("StartTag", xpp.getName()); 
      break;      
     case XmlPullParser.END_TAG: 
      Log.e("EndTag", xpp.getName()); 
        //When you need to stop parsing use this 
        break outerloop; 
      break; 
    } 
    eventType = xpp.next(); 
}