0

我需要从“条件”中提取值,但在“current_conditions”下。这是我现在拥有的代码。它从条件中提取值,但从“forecast_conditions”中提取值。顺便说一句,我正在使用 SAXParser。

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

这是 XML。

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

<forecast_conditions>
    <condition data="Partly Sunny"/>
</forecast_conditions>
4

2 回答 2

1

您使用哪个解析器?如果您使用 XmlPullParser(或任何 SAX 样式的解析器),您可以在遇到current_conditionsSTART_TAG 时设置一个标志,并在检查condition. current_conditions遇到END_TAG时不要忘记重置标志。

于 2012-04-26T04:53:03.967 回答
0

我将第二个 XmlPullParser - 这很容易理解。

这是您的案例的一些代码(未经测试)

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();
    }
}
于 2012-04-26T07:44:21.950 回答