原理:从网站上获得xml格式数据,并显示
天气api
http://webservice.webxml.com.cn/Webservices/WeatherWebService.asmx/getWeatherbyCityName?theCityName
http://www.webxml.com.cn/images/weather/b_24.gif
新建singleView工程,名为WeatherDemo
修改
- (void)viewDidLoad
{
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *url=[@"http://webservice.webxml.com.cn/Webservices/WeatherWebService.asmx/getWeatherbyCityName?theCityName=北京"stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *xml=[NSStringstringWithContentsOfURL:[NSURLURLWithString:url]encoding:NSUTF8StringEncodingerror:nil];
GDataXMLDocument *doc=[[[GDataXMLDocumentalloc]initWithXMLString:xmloptions:0error:nil]autorelease];
NSArray *nodes=[doc.rootElementchildren];
for (GDataXMLNode *nodein nodes) {
NSLog(@"node=%@",node);
}
}
XML解析选中项目,选中“Build Settings”标签页,将顶部的“Basic”标签切换到"All"
找到“Paths\Header Search Paths”项,并添加“/usr/include/libxml2”到列表中
找到“Linking\Other Linker Flags”项,并添加"-lxml2"到列表中
Frameworks:libxml
将GDataXml加入工程
修改xib文件:
一个label用来显示日期,一个用来显示温度。
关联成员变量:_todayInfo,_todayTemp,_nextInfo,_nextTemp.
- (void)viewDidLoad
{
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *url=[@"http://webservice.webxml.com.cn/Webservices/WeatherWebService.asmx/getWeatherbyCityName?theCityName=北京"stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *xml=[NSStringstringWithContentsOfURL:[NSURLURLWithString:url] encoding:NSUTF8StringEncodingerror:nil];
GDataXMLDocument *doc=[[[GDataXMLDocumentalloc] initWithXMLString:xmloptions:0error:nil]autorelease];
NSArray *nodes=[doc.rootElementchildren];
GDataXMLNode *n1=[nodes objectAtIndex:6];
_todayInfo.text=[n1stringValue];
GDataXMLNode *n2=[nodes objectAtIndex:5];
_todayTemp.text=[n2stringValue];
GDataXMLNode *n3=[nodes objectAtIndex:13];
_nextInfo.text=[n3stringValue];
GDataXMLNode *n4=[nodes objectAtIndex:12];
_nextTemp.text=[n4stringValue];
}
源码地址:http://download.csdn.net/detail/cloud95/5192555