导入libxml2,使用第三方AFNetworking网络请求,第三方XML解析GData
GData需要的配置 Build Settings 里搜索,添加如下
如果是ARC ,需要加上 -fno-objc-arc
首先找一个xml网址使用AFNetworking请求得到NSData数据
#define HTTP_URL_GET @"http://lab.hudong.com/ipad/zutujingxuan.xml"
- (void)getRequest {
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc]
init];
//返回数据解析
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//AFJSONResponseSerializer responseObject就是jeson解析后的对象(有可能是字典)
//AFXMLParserResponseSerializer responseObject就是NSXMLPareser对象
//AFHTTPRequestOperationManager responseObject就是NSData [manager GET:HTTP_URL_GET parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"%@",responseObject);
// NSXMLParser
[self xml:responseObject];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"error:%@.",error.localizedDescription);
}]; }
先打开火狐浏览器看xml的层次结构(复制网址在火狐浏览器上打开)
使用GData解析,记住一层一层解析
- (void)xml:(NSData *)data {
//创建一个解析对象
GDataXMLDocument *document = [[GDataXMLDocument alloc]initWithData:data options: error:nil];
//获取根节点
GDataXMLElement *rootElement = document.rootElement;
NSLog(@"name: %@,stringvaule: %@",rootElement.name,rootElement.stringValue);
GDataXMLElement *channeName = [rootElement elementsForName:@"channelName"].firstObject;
NSLog(@"%@---%@",channeName.name,channeName.stringValue);
//取多组
// //docInfo 直接跳过前面的子节点,知道取到名字对应的子节点
// NSArray *docInfos = [rootEiement nodesForXPath:@"//docInfo" error:nil]
NSArray *docInfos = [[rootElement elementsForName:@"docList"].firstObject elementsForName:@"docInfo"]; for (GDataXMLElement *docInfoElement in docInfos) {
NSMutableDictionary * dic = [NSMutableDictionary dictionary];
for (GDataXMLElement *elment in [docInfoElement children]) {
[dic setObject:elment.stringValue forKey:elment.name];
}
[_allInfos addObject:dic];
}
NSLog(@"%@",_allInfos);
}
最后是用一个全局的NSMutableArray接收打印,~