XML & JSON 簡介javascript
// 1. 開始解析XML文檔php
- (void)parserDidStartDocument:java
// 2. 開始解析某個元素,會遍歷整個XML,識別元素節點名稱json
- (void)parser:didStartElement:namespaceURI:qualifiedName:attributes:數組
// 3. 文本節點,獲得文本節點裏存儲的信息數據,對於大數據可能會接收屢次!爲了節約內存開銷服務器
- (void)parser:foundCharacters:網絡
// 4. 結束某個節點,存儲從parser:foundCharacters:方法中獲取到的信息數據結構
- (void)parser:didEndElement:namespaceURI:qualifiedName:app
注意:在解析過程當中,二、三、4三個方法會不停的重複執行,直到遍歷完成爲止ide
// 5. 解析XML文檔結束
- (void)parserDidEndDocument:
// 6. 解析出錯
- (void)parser:parseErrorOccurred:
實例代碼
#import "DemoViewController.h"#import "UIImageView+WebCache.h"#import "Video.h"#import "VideoCell.h"#define kBaseURL @"http://192.168.3.251/~apple"@interface DemoViewController () <NSXMLParserDelegate>{ NSMutableArray *_dataList; UIImage *_placeHolderImage; // 如下是XML解析須要的成員變量 NSMutableString *_elementString; // 拼接的字符串 Video *_currentVideo; // 當前解析的視頻模型對象}@end@implementation DemoViewController/** 數據處理過程 1> 從服務器上加載不一樣類型的數據JSON/XML 2> 將接收到的數據轉換成對象數組 3> 在表格中顯示數組內容 XML解析的六個步驟 1. 開始解析文檔,在這裏作初始化工做 2.3.4會循環執行,一直到XML文檔解析完畢 2. 解析一個節點 3. 查找節點內容,可能會屢次 4. 節點完成 5. 解析完成,作收尾工做 6. 解析出錯,清理中間數據 */- (void)viewDidLoad{ [super viewDidLoad]; // 設置標題 self.title = (_loadType == kLoadDataJSON) ? @"JSON" : @"XML"; _placeHolderImage = [UIImage imageNamed:@"user_default"]; if (_loadType == kLoadDataJSON) { [self loadJSON]; } else { [self loadXML]; }}#pragma mark - 表格的數據源方法- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ return _dataList.count;}- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString *ID = @"MyCell"; VideoCell *cell = [tableView dequeueReusableCellWithIdentifier:ID]; // 設置單元格 Video *video = _dataList[indexPath.row]; cell.videoTitleLabel.text = video.name; cell.teacherLabel.text = video.teacher; cell.lengthLabel.text = video.lengthStr; // 設置圖像 // 完整的URL NSString *imageURLStr = [NSString stringWithFormat:@"%@%@", kBaseURL, video.imageURL]; NSURL *url = [NSURL URLWithString:imageURLStr]; [cell.icon setImageWithURL:url placeholderImage:_placeHolderImage]; return cell;}#pragma mark - 數據加載方法- (void)loadJSON{ // 1. 從服務器獲取數據 GET // 1) url NSURL *url = [NSURL URLWithString:@"http://192.168.3.251/~apple/itcast/videos.php?format=json"]; // 2) request NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:2.0f]; // 3) 鏈接同步,可讓用戶先有內容可看 NSError *error; // NSData存放的是二進制的數據 NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error]; // 判斷返回結果 if (data != nil) { // 正常返回數據// NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];// NSLog(@"%@", result); // 反序列化 NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; NSLog(@"%@", array); // 技巧,從網絡上接收到JSON,爲了方便閱讀,能夠將其反序列化以後,保存至文件 [array writeToFile:@"/Users/apple/Desktop/123.plist" atomically:YES]; // 將數據轉換成模型,並保存至表格須要的數組中 NSMutableArray *arrayM = [NSMutableArray arrayWithCapacity:array.count]; for (NSDictionary *dict in array) { Video *video = [[Video alloc] init]; [video setValuesForKeysWithDictionary:dict]; [arrayM addObject:video]; } _dataList = arrayM; } else if (error == nil) { NSLog(@"返回空數據"); } else { NSLog(@"%@", error.localizedDescription); }}#pragma mark 解析XML- (void)loadXML{ // 1. 從服務器獲取數據 GET // 1) url NSURL *url = [NSURL URLWithString:@"http://192.168.3.251/~apple/itcast/videos.php?format=xml"]; // 2) request NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:2.0f]; // 3) 鏈接同步,可讓用戶先有內容可看 NSError *error; // NSData存放的是二進制的數據 NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error]; // 2. XML解析 // 1) 解析器 NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data]; // 2) 設置代理 parser.delegate = self; // 3)開始解析 [parser parse];}#pragma mark - XML解析方法// 1. 開始解析文檔,在這裏作初始化工做- (void)parserDidStartDocument:(NSXMLParser *)parser{ NSLog(@"開始解析文檔"); // 數組尚未被初始化,初始化數組 _dataList = [NSMutableArray array]; _elementString = [NSMutableString string];}// 2.3.4會循環執行,一直到XML文檔解析完畢// 2. 解析一個節點- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{ NSLog(@"節點開始 %@ %@", elementName, attributeDict); if ([elementName isEqualToString:@"video"]) { // 新建一個視頻模型對象 _currentVideo = [[Video alloc] init]; // 取視頻ID _currentVideo.videoId = [attributeDict[@"videoId"] integerValue]; } // 清空拼接字符串 [_elementString setString:@""];}// 3. 查找節點內容,可能會屢次- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{ NSLog(@"開始查找內容 %@", string); // 拼接字符串 [_elementString appendString:string];}// 4. 節點完成- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{ NSLog(@"節點完成 %@ %p", elementName, _elementString); NSString *result = [NSString stringWithString:_elementString]; if ([elementName isEqualToString:@"video"]) { // 對象的屬性填充完畢,添加到數組 [_dataList addObject:_currentVideo]; } else if ([elementName isEqualToString:@"length"]) { _currentVideo.length = [result integerValue]; } else if (![elementName isEqualToString:@"videos"]) { // 利用KVC給字符串類型的屬性賦值 [_currentVideo setValue:result forKey:elementName]; } // else if ([elementName isEqualToString:@"name"]) {// _currentVideo.name = result;// } else if ([elementName isEqualToString:@"length"]) {// _currentVideo.length = [result integerValue];// } else if ([elementName isEqualToString:@"videoURL"]) {// _currentVideo.videoURL = result;// } else if ([elementName isEqualToString:@"imageURL"]) {// _currentVideo.imageURL = result;// } else if ([elementName isEqualToString:@"desc"]) {// _currentVideo.desc = result;// } else if ([elementName isEqualToString:@"teacher"]) {// _currentVideo.teacher = result;// }}// 5. 解析完成,作收尾工做- (void)parserDidEndDocument:(NSXMLParser *)parser{ NSLog(@"解析完成"); NSLog(@"%@", _dataList);}// 6. 解析出錯,清理中間數據- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError{ NSLog(@"%@", parseError.localizedDescription); // 一旦解析發生錯誤,須要把解析過程當中生成的記錄所有清除,以避免形成沒必要要的麻煩 [_dataList removeAllObjects];}@end