2013-06-29 68 views
0

我使用解析yahooweather API的SAXParser使用SAX解析器具有兩個節點解析文件具有相同的名稱

<yweather:forecast day="Sun" date="30 Jun 2013" low="22" high="34" text="Sunny" code="32"/> 
<yweather:forecast day="Mon" date="1 Jul 2013" low="22" high="33" text="Sunny" code="32"/> 
<yweather:forecast day="Tue" date="2 Jul 2013" low="22" high="33" text="Partly Cloudy" code="30"/> 
<yweather:forecast day="Wed" date="3 Jul 2013" low="23" high="36" text="Sunny" code="32"/> 

使用此代碼:

@Override 
public void startElement(String uri, String localName, String qName, 
     Attributes attributes) throws SAXException { 

    if (qName.equalsIgnoreCase("yweather:forecast")){ 

     day1.add(attributes.getValue("day")); 
     day1.add(attributes.getValue("date")); 
     day1.add(attributes.getValue("low")); 
     day1.add(attributes.getValue("high")); 
     day1.add(attributes.getValue("text")); 
     day1.add(attributes.getValue("code"));  

     info.setweather(day1.get(0),day1.get(1),day1.get(2),day1.get(3),day1.get(4),day1.get(5)); 
    } 
} 

我現在可以得到第一天。但我只想得到第二天,而不是其他四天,並把它放在另一個陣列。

回答

0

假設XML節點的順序就足以找出第二天是什麼:

簡單地計算多久你發現了一個yweather:forecast元素的開始。

private int currentDay; 

@Override 
public void startElement(String uri, String localName, String qName, 
     Attributes attributes) throws SAXException { 

    if (qName.equalsIgnoreCase("yweather:forecast")){ 
     if (currentDay++ != 1) return; 
     // rest of your code 

還在每個文檔開始或結束時重置或初始化計數器。

相關問題