[ios]xml, json解析
1.xml解析
要解析的xml文件
<?xml version="1.0" encoding="UTF-8"?>
<Books>
<Book ISBN="032188728X">
<title>Programming in Objective-C</title>
<author>Stephen G. Kochan</author>
<summary>Programming in Objective-C is a concise, carefully written tutorial on the basics of Objective-C and object-oriented programming for Apple's iOS and OS X platforms.</summary>
</Book>
<Book ISBN="0321884213">
<title>The Core iOS 6 Developer Cookbook</title>
<author>Erica Sadun</author>
<summary>The Core iOS 6 Developer Cookbook brings together reliable, proven solutions for the heart of day-to-day iOS 6 development.</summary>
</Book>
<Book ISBN="0321535022">
<title>Cocoa Design Patterns</title>
<author>Erik M. Buck</author>
<summary>Unlocking the Secrets of Cocoa and Its Object-Oriented Frameworks.</summary>
</Book>
</Books>
第一种方法:NSXMLParser (SAX)
第一步:首先要实现NSXMLParserDelegate
@interface XMLEngine()<NSXMLParserDelegate>
#pragma mark -NSXMLParser
-(BOOL) parseURL:(NSURL *)url{
//xml生成器
NSXMLParser *parser=[[NSXMLParser alloc] initWithContentsOfURL:url ];
//url为本地的xml文件路径
[parser setDelegate:self];
BOOL rc=[parser parse];
if(!rc)
{
NSError *err=[parser parserError];
NSLog(@" XMLParser parse error:=%@",[err localizedDescription]);
}
[parser release];
[self dumpBooks];
return rc;
}
#pragma mark -NSXMLParserDelegate
-(void) parserDidStartDocument:(NSXMLParser *)parser
{
NSLog(@"%s", __FUNCTION__);
}
-(void) parserDidEndDocument:(NSXMLParser *)parser
{
NSLog(@"%s", __FUNCTION__);
}
-(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
//sent when the parser finds an element start tag.
NSLog(@"%s", __FUNCTION__);
NSLog(@"elementName=%@",elementName);
NSLog(@"namespaceURI=%@",namespaceURI);
NSLog(@"qName=%@",qName);
NSLog(@"attributeDict=%@",attributeDict);
if([elementName isEqualToString:@"Books"])
{
self.books=[[[NSMutableArray alloc] initWithCapacity:3 ] autorelease ];
}else if([elementName isEqualToString:@"Book"]) {
self.book=[[[Book alloc] init ] autorelease];
self.book.ISBN=[attributeDict objectForKey:@"ISBN"];
}
}
-(void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
NSLog(@"%s",__FUNCTION__);
if(nil==self.curElementValue)
{
self.curElementValue=[[[NSMutableString alloc] initWithString:string]
autorelease];
}else {
[self.curElementValue appendString:string];
}
[self.curElementValue setString:[self.curElementValue stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
}
-(void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
NSLog(@"%s", __FUNCTION__);
NSLog(@"elementName=%@", elementName);
NSLog(@"namespaceURI=%@", namespaceURI);
NSLog(@"qName=%@", qName);
if([elementName isEqualToString:@"Books"])
{
}else if ([elementName isEqualToString:@"Book"]) {
[self.books addObject:self.book];
_book=nil;
}else {
[self.book setValue:self.curElementValue forKey:elementName];
self.curElementValue=nil;
}
}
-(void) parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
{
NSLog(@"%s", __FUNCTION__);
NSLog(@"parserError=%@",[parseError localizedDescription]);
}
第二种方法:GDataXMLNode
要下载引入GDataXMLNode文件
根据下面提示配置路径
// libxml includes require that the target Header Search Paths contain
//
// /usr/include/libxml2
//
// and Other Linker Flags contain
//
// -lxml2
#pragma mark-GDataXML
-(BOOL) parseURLByGDataXML:(NSURL *)url
{
NSError *err=nil;
NSData *xmlData=[NSData dataWithContentsOfURL:url];
GDataXMLDocument *doc=[[GDataXMLDocument alloc] initWithData:xmlData options:0 error:&err ];
if(nil==doc)
{
NSLog(@"Error:%@",[err localizedDescription]);
return NO;
}
self.books=[[NSMutableArray alloc] initWithCapacity:3 ];
NSArray * array=nil;
array =[doc nodesForXPath:@"//Books/Book" error:&err];
for(GDataXMLElement *item in array)
{
self.book=[[[Book alloc] init] autorelease];
GDataXMLNode * node=[item attributeForName:@"ISBN"];
self.book.ISBN=node.stringValue;
NSArray *titles=[item elementsForName:@"title"];
if(titles.count>0)
{
GDataXMLElement * firstTitle=[titles objectAtIndex:0];
self.book.title=firstTitle.stringValue;
}
NSArray *authors=[item elementsForName:@"author"];
if([authors count]>0)
{
GDataXMLElement *firstAuthor=(GDataXMLElement *)[authors objectAtIndex:0];
self.book.author=firstAuthor.stringValue;
}
NSArray *summarys=[item elementsForName:@"summary"];
if([summarys count]>0)
{
GDataXMLElement *firstSumary=(GDataXMLElement*)[summarys objectAtIndex:0];
self.book.summary=firstSumary.stringValue;
}
[self.books addObject:self.book];
self.book=nil;
}
[doc release];
[self dumpBooks];
return YES;
}
两者比较:NSXMLParser 写起来麻烦,效率相对来说高
GDataXMLNode 简单易懂,但比较耗内存(在DOM解析方式中,先将XML转化成对象然后保存到内存)
2.json解析
要解析的json文件
{"Books":[{"Book":{"ISBN":"032188728X", "title":"Programming in Objective-C", "author":"Stephen G. Kochan", "summary":"good"}}, {"Book":{"ISBN":"0321884213", "title":"The Core iOS 6 Developer Cookbook", "author":"Erica Sadun", "summary":"better"}}, {"Book":{"ISBN":"0321535022", "title":"Cocoa Design Patterns", "author":"Erik M. Buck", "summary":"best"}}]}
解析方法1:NNJSONSerializaion
#pragma mark-NNJSONSerializaion
-(BOOL) parseURL:(NSURL *)url
{
NSError * err=nil;
NSData * data=[NSData dataWithContentsOfURL:url];
NSDictionary *json=[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&err];
if(![NSJSONSerialization isValidJSONObject:json])
{
NSLog(@"NSJSONSerializaiton invalid!");
return NO;
}
NSArray *arry=[json objectForKey:@"Books"];
for (int i=0; i<[arry count]; i++) {
NSLog(@"%@",[arry objectAtIndex:i]);
}
for (NSDictionary * item in arry) {
NSDictionary* dic = [item objectForKey:@"Book"];
Book * b=[[[Book alloc] init ]autorelease ];
b.ISBN=[dic objectForKey:@"ISBN"];
b.title = [dic objectForKey:@"title"];
b.author = [dic objectForKey:@"author"];
b.summary = [dic objectForKey:@"summary"];
[self.books addObject:b];
}
return YES;
}
解析方法1:JSONKit
首先引进JSONKit文件
-(BOOL) parseURLByJSONKit:(NSURL *)url
{
NSData *data=[NSData dataWithContentsOfURL:url];
JSONDecoder * decoder=[JSONDecoder decoderWithParseOptions:(JKParseOptionNone)];
NSDictionary * json=[decoder objectWithData:data];
NSArray* array = [json objectForKey:@"Books"];
for (NSDictionary* item in array) {
NSDictionary* dic = [item objectForKey:@"Book"];
Book* b = [[[Book alloc] init] autorelease];
b.ISBN = [dic objectForKey:@"ISBN"];
b.title = [dic objectForKey:@"title"];
b.author = [dic objectForKey:@"author"];
b.summary = [dic objectForKey:@"summary"];
[self.books addObject:b];
}
return YES;
}
性能比较