標籤:
<pre name="code" class="objc">/*---------------------------XML_SAX解析-------------------------------*///XML SAX解析- (IBAction)XML_SAX:(id)sender{ NSData *da = [[NSData alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"megage" ofType:@"txt"]]; //第一步,建立xml解析 NSXMLParser *Parserdata = [[NSXMLParser alloc] initWithData:da]; //第二步設定代理 Parserdata.delegate = self; //第三步 啟動解析 [Parserdata parse]; NSLog(@"點我");}/*---------------------------XML_SAX代理方法-------------------------------*///開始解析------------->>>啟動解析的時候走代理方法- (void)parserDidStartDocument:(NSXMLParser *)parser{ //1.在開始解析的時候初始化接收資訊的數組,為了不佔用記憶體 self.megArray = [NSMutableArray array];}//開始解析某個節點的時候- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{ //小1.把他的節點接收合來 self.elementString = elementName; if([elementName isEqualToString:@"message"]) { Recorce *meg = [[Recorce alloc] init]; [self.megArray addObject:meg]; }}//找到內容(節點)- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{ Recorce *meg = [self.megArray lastObject]; //通過節點加入內容 [meg setValue:string forKey:self.elementString]; }//結束解析某個節點- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{ self.elementString = nil;}//完畢解析- (void)parserDidEndDocument:(NSXMLParser *)parser{ for (Recorce *me in self.megArray) { NSLog(@"%@",me); } }//解析錯誤發生的時候- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError{ }
- (IBAction)XML_DOM:(id)sender{ NSData *data = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"megage" ofType:@"txt"]]; //擷取資料 GDataXMLDocument *document = [[GDataXMLDocument alloc] initWithData:data options:0 error:nil]; //找到根節點 GDataXMLElement *Rootelement = document.rootElement; self.megArray = [NSMutableArray array]; //遍曆根節點中的子節點, for ( GDataXMLElement *em in Rootelement.children ) { message *meg = [[message alloc] init]; for (GDataXMLElement *GE in em.children) { [meg setValue:GE.stringValue forKey:GE.name]; } [self.megArray addObject:meg]; NSLog(@"%@",meg); } }
- (IBAction)JSON_KIT:(id)sender{ //獲得路徑 NSData *data = [[NSData alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"content" ofType:@"txt"]]; //獲得資料(第三方) NSArray *dataArray = [data objectFromJSONData]; NSLog(@"%@",dataArray); }
- (IBAction)JSON:(id)sender{ NSData *data = [[NSData alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"content" ofType:@"txt"]]; NSArray *dataArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
著作權聲明:本文部落格原創文章,部落格,未經同意,不得轉載。
IOS JSON/XML解析