Android解析XML之XmlPullParser

    public void getXML(String url) throws XmlPullParserException,IOException,URISyntaxException
    {
    	String xmlString=downloadXML(url);	
    	
    	XmlPullParserFactory factory=XmlPullParserFactory.newInstance();
    	
    	factory.setNamespaceAware(true);
    	
    	XmlPullParser parser=factory.newPullParser();
    	
    
    	
    	parser.setInput(new StringReader(xmlString));
    	
    	int eventType=parser.getEventType();
    	
    	 List<Forecast_conditions> conditionsList=new ArrayList<Forecast_conditions>();
    	 Forecast_conditions forecast_conditions=null;
    	
    	
    	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 "+parser.getName());
				
				
				
				
				if (parser.getName().equals("forecast_conditions")) 
				{
					forecast_conditions=new Forecast_conditions();
				}
					
					if (parser.getName().equals("day_of_week")) {
						forecast_conditions.setDay_of_week(parser.getAttributeValue(0));
						
					}else if (parser.getName().equals("low")) {
						
						forecast_conditions.setLow(parser.getAttributeValue(0));
					}else if (parser.getName().equals("high")) {
						
						forecast_conditions.setHigh(parser.getAttributeValue(0));
					}else if (parser.getName().equals("icon")) {
						
						try {
							forecast_conditions.setIcon(parser.getAttributeValue(0));
						} catch (Exception e) {
							// TODO: handle exception
						}
						
						
					}else if (parser.getName().equals("condition")) {
						
						try {
							 forecast_conditions.setCondition(parser.getAttributeValue(0));	
						} catch(Exception e){
							
						}
						
					   
					    
					    
					}
				
				
				
				
			   /*	int size=parser.getAttributeCount();
				
				for (int i = 0; i < size; i++) {
					System.out.println("AttributeName "+parser.getAttributeName(i));
					System.out.println("AttributeValue"+parser.getAttributeValue(i));
				} */
			}else if(eventType== XmlPullParser.END_TAG){
				System.out.println("End Tag "+parser.getName());
				if (parser.getName().equals("forecast_conditions")) {
					conditionsList.add(forecast_conditions);
				}
				
			}else if(eventType==XmlPullParser.TEXT){
				System.out.println("Text "+parser.getText());
			}
			
			eventType=parser.next();
		}
    	System.out.println("End Document");
    	
    	
    	bindToListView(conditionsList);
    	//XmlUtils.
			
		
    }
 
本实例是不完整实例。 初学Android, 很多地方不规范。  仅供参考。

  

posted @ 2011-10-20 22:31 Sir。 阅读(...) 评论(...) 编辑 收藏