2012-04-26 4 views
0

"condition"の値を抽出する必要がありますが、 "current_conditions"の値は抽出する必要があります。 ここに私が今持っているコードがあります。条件から "forecast_conditions"から値を抽出します。ところで私はSAXParserを使用しています。より具体的なXML解析方法

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> 
+0

この1つはhttp://stackoverflow.com/questions/4827344/how-to-parse-xml-using-the-sax-見ますパーサー –

答えて

1

どのパーサーを使用しますか? XmlPullParser(または任意のSAXスタイルパーサ)を使用する場合は、current_conditions START_TAGが発生したときにフラグを設定し、conditionをチェックするときにこのフラグが設定されているかどうかを確認できます。 current_conditions END_TAGに遭遇したときにフラグをリセットすることを忘れないでください。

+0

私はSAXParserを使用します。どのようにフラグを設定するのですか? – MikeC

0

2番目の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(); 
    } 
}