2014-11-06 65 views
0

我從yahoo weather獲取天氣信息,我可以從文檔解析溫度信息,但有問題請我不能說我使用NSXMLParser<escription>元素獲取圖像的URL即如何從雅虎天氣預報XML文檔中獲取圖片網址?

<description> 
<![CDATA[ 
<img src="http://l.yimg.com/a/i/us/we/52/28.gif"/><br /> <b>Current Conditions:</b><br /> Mostly Cloudy, 61 F<BR /> <BR /><b>Forecast:</b><BR /> Thu - Showers. High: 66 Low: 48<br /> Fri - AM Light Rain. High: 52 Low: 37<br /> Sat - Partly Cloudy. High: 61 Low: 47<br /> Sun - AM Clouds/PM Sun. High 
]]> 
<![CDATA[ 
: 66 Low: 48<br /> Mon - PM Showers. High: 62 Low: 50<br /> <br /> <a href="http://us.rd.yahoo.com/dailynews/rss/weather/Hakuba_Station__JP/*http://weather.yahoo.com/forecast/JAXX0105_f.html">Full Forecast at Yahoo! Weather</a><BR/><BR/> (provided by <a href="http://www.weather.com" >The Weather Channel</a>)<br/> 
]]> 
</description> 

用於解析MXL文件。

回答

1

基於@ haras.prasad回答我解決了使用NSXMLParser委託和NSRegularExpression

- (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { 
    NSString *cdataString = [[NSString alloc] initWithData:CDATABlock encoding:NSUTF8StringEncoding]; 
    // Do extraction of image src here 
    NSError* error; 
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(<img\\s[\\s\\S]*?src\\s*?=\\s*?['\"](.*?)['\"][\\s\\S]*?>)+?" 
                      options:NSRegularExpressionCaseInsensitive 
                      error:&error]; 

    NSString *imageUrlString = nil; 
    NSTextCheckingResult *match = [regex firstMatchInString:cdataString options:0 range:NSMakeRange(0, [cdataString length])]; 
    if (match) 
    { 
     imageUrlString = [cdataString substringWithRange:[match rangeAtIndex:2]]; 

     self.iconUrl = imageUrlString; 
    } 

} 
+0

我認爲這將工作.. :) – 2014-11-07 02:28:46

+0

燁我得到它的工作..感謝哥們。 – Blios 2014-11-12 09:13:54

0

你可以得到CDATA字符串:

NSString *prefix = @"<![CDATA["; 
if ([xmlString hasPrefix:prefix]) { 
    NSString *cdataString = [_factString substringWithRange:NSMakeRange((prefix.length+1), xmlString.length - 3 -(prefix.length+1))]; 
    // Do stuff with CDATA here... 
    NSLog(@"%@", cdataString); 
} 
1

在你NSXMLParserDelegate,你可以調用委託方法foundCDATA和處理數據在那裏。

- (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { 
     NSString *cdataString = [[NSString alloc] initWithData:CDATABlock encoding:NSUTF8StringEncoding]; 
     // Do extraction of image src here 
} 

您可以檢查委託方法這裏的文檔:NSXMLParserDelegate

+0

這個問題我需要解析HTML獲取IMG SRC?如果可以,請給我一些參考資料,說明如何做到這一點? – Blios 2014-11-06 10:30:01

+0

你還需要一個解析器方法嗎? – 2014-11-07 01:28:47