我从yahoo weather获取天气信息,并且我能够解析文档中的温度信息,但是从<escription>
元素获取图片网址时遇到问题,即
<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>
请注意,我没有使用NSXMLParser
来解析MXL文档。
答案 0 :(得分: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
答案 1 :(得分: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;
}
}
答案 2 :(得分: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);
}