0

I need to extract the value from "condition" but the one that's under "current_conditions". Here is the code I have right now. It extracts value from condition but from "forecast_conditions". By the way i'm using SAXParser.

if (localName.equals("condition")) {
    String con = attributes.getValue("data");
    info.setCondition(con);
}

Here is the XML.

<current_conditions>
    <condition data="Clear"/>        
</current_conditions>

<forecast_conditions>
    <condition data="Partly Sunny"/>
</forecast_conditions>
MikeC
  • 255
  • 4
  • 16

2 Answers2

1

Which parser do you use? If you use XmlPullParser (or any SAX style parser), you can set a flag when you encounter current_conditions START_TAG and check whether this flag is set when you check for condition. Don't forget to reset the flag when you encounter current_conditions END_TAG.

Rajesh
  • 15,724
  • 7
  • 46
  • 95
0

I'll second XmlPullParser - it's very easy to understand.

Here is some code for you case (not tested)

public void parser(InputStream is) {
    XmlPullParserFactory factory;
    try {
        factory = XmlPullParserFactory.newInstance();
        factory.setNamespaceAware(true);
        XmlPullParser xpp = factory.newPullParser();
        xpp.setInput(is, null);

        boolean currentConditions = false;
        String curentCondition;

        int eventType = xpp.getEventType();
        while (eventType != XmlPullParser.END_DOCUMENT) {
            if (eventType == XmlPullParser.START_TAG) {
                if (xpp.getName().equalsIgnoreCase("current_conditions")) {
                currentConditions = true;
                } 
                else if (xpp.getName().equalsIgnoreCase("condition") && currentConditions){
                    curentCondition = xpp.getAttributeValue(null,"Clear");
                }
            } else if (eventType == XmlPullParser.END_TAG) {
                if (xpp.getName().equalsIgnoreCase("current_conditions"))
                    currentConditions = false;
            } else if (eventType == XmlPullParser.TEXT) {
            }
            eventType = xpp.next();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Sver
  • 3,349
  • 6
  • 32
  • 53