使用具有两个节点的sax解析器解析文件具有相同的名称

时间:2013-06-29 16:30:59

标签: java android

我正在使用 saxparser解析 yahooweather api

<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));
    }
}

我现在可以获得第一天了。但我只希望第二天,也不是其他四天,并把它放在另一个阵列。

1 个答案:

答案 0 :(得分: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

还要在每个文档的开头或结尾处重置或启动计数器。