1

数日間インターネットを検索しましたが、簡潔な答えが見つかりません。ハードコードされた郵便番号の気温を表示する簡単な天気予報アプリを作成したいと思います。

これがXMLです

<data>
<request>
<type>Zipcode</type>
<query>08003</query>
</request>
<current_condition>
<observation_time>08:29 PM</observation_time>
<temp_C>11</temp_C>
<temp_F>52</temp_F>
<weatherCode>143</weatherCode>
<weatherIconUrl>
<![CDATA[
http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0006_mist.png
]]>
</weatherIconUrl>
<weatherDesc>
<![CDATA[ Mist ]]>
</weatherDesc>
<windspeedMiles>4</windspeedMiles>
<windspeedKmph>7</windspeedKmph>
<winddirDegree>210</winddirDegree>
<winddir16Point>SSW</winddir16Point>
<precipMM>0.0</precipMM>
<humidity>87</humidity>
<visibility>5</visibility>
<pressure>1013</pressure>
<cloudcover>100</cloudcover>
</current_condition>
<weather>
<date>2012-12-08</date>
<tempMaxC>13</tempMaxC>
<tempMaxF>55</tempMaxF>
<tempMinC>9</tempMinC>
<tempMinF>48</tempMinF>
<windspeedMiles>6</windspeedMiles>
<windspeedKmph>9</windspeedKmph>
<winddirection>W</winddirection>
<winddir16Point>W</winddir16Point>
<winddirDegree>260</winddirDegree>
<weatherCode>122</weatherCode>
<weatherIconUrl>
<![CDATA[
http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0004_black_low_cloud.png
]]>
</weatherIconUrl>
<weatherDesc>
<![CDATA[ Overcast ]]>
</weatherDesc>
<precipMM>3.1</precipMM>
</weather>
</data>

私がやりたいのは、*temp_F*を抽出してNSStringに保存することだけです。

4

2 に答える 2

2

XMLに1回だけ表示される単一の要素の単一の値だけが必要な場合は、本格的なXMLパーサーを使用する代わりに、単純な文字列検索を実行します。

@"<temp_F>"サブストリングとサブストリングの範囲を取得し@"</temp_F>"、その間の値を取得します。

于 2012-12-08T21:59:20.357 に答える
1

NSXMLParserの使用についてはすでに説明したので、それを使用してください。プロトコルを実装するようにデリゲートを設定します

 @interface MyClass : NSObject <NSXMLParserDelegate>

次のようなxmlエントリの開始タグ(この場合はそうであるように見えます)に注意してください。

 - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {

      if ( [elementName isEqualToString:@"temp_F"] ) {
           // Set flag and reset string
           self.foundTargetElement = true;
           if ( self.myMutableString ) {
                self.myMutableString = nil;
                self.myMutableString = [[NSMutableString alloc] init];
           }
      }
 }

次の実装

 - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
       if ( self.foundTargetElement ) {
             [self.myMutableString appendString:string];
       }     
 }

上記と同じパターンを使用して、タグ()を監視し、その値を文字列に追加するか、データに対して他の必要な操作を行います。

 - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {

      self.foundTargetElement = false;

      // Do something with your result, or
      // Wait until entire document has been parsed.
 }

それがあなたのためにうまくいくかどうか私に知らせてください。

于 2012-12-08T22:30:45.710 に答える