简体   繁体   中英

parsing file using sax parser with two nodes have the same name

I'm parsing yahooweather api using saxparser

<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"/>

using this code:

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

I can now get the first day. But I only want to get the second day, also not the other four days and put it in another array .

Assuming that the order of the XML nodes is enough to figure out what the second day is:

Simply count how often you found the start of a yweather:forecast element.

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

Also reset or init the counter at each document start or end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM