工程截图:
ViewController.h
// // ViewController.h // NSXMLParserDemo // // Created by Fox on 12-3-15. // Copyright (c) 2012年 __MyCompanyName__. All rights reserved. // #import@interface ViewController : UIViewController - (void)parseXMLFileAtURL:(NSURL *)URL parseError:(NSError **)error; @end
ViewController.m
// // ViewController.m // NSXMLParserDemo // // Created by Fox on 12-3-15. // Copyright (c) 2012年 __MyCompanyName__. All rights reserved. // /**/ #import "ViewController.h" @implementation ViewController - (void)viewDidLoad { NSLog(@"viewDidLoad"); [super viewDidLoad]; NSMutableString *Strxml=[NSMutableString stringWithString:@" "]; NSData *data=[NSData dataWithBytes:[Strxml UTF8String] length:[Strxml length]]; NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data]; //设置XML数据 [parser setDelegate:self]; [parser setShouldProcessNamespaces:NO]; [parser setShouldReportNamespacePrefixes:NO]; [parser setShouldResolveExternalEntities:NO]; [parser parse];//开始解析 } #pragma mark NSXMLParserDelegate methods /* *开始解析XmL */ - (void)parserDidStartDocument:(NSXMLParser *)parser { // 解析开始时的处理 NSLog(@"parserDidStartDocument"); } /* *遍历xml节点 */ - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { NSLog(@"didStartElement"); NSLog(@"Element:%@",elementName); //NSLog(@"qualifiedName:%@",qName); if (qName) { elementName = qName; } if ([elementName isEqualToString:@"user"]) { // 输出属性值 NSLog(@"Name is %@ , Age is %@", [attributeDict objectForKey:@"name"], [attributeDict objectForKey:@"age"]); } } /* *当遇到结束标记时,调用该方法 */ - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { NSLog(@"didEndElement"); NSLog(@"EndElement:%@",elementName); //NSLog(@"qualifiedName:%@",qName); if (qName) { elementName = qName; } } /* *当xml节点有值时,调用此函数 */ - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { NSLog(@"foundCharacters"); NSLog(@"Value:%@",string); } /* *结束XML解析 */ - (void)parserDidEndDocument:(NSXMLParser *)parser { NSLog(@"parserDidEndDocument"); } @end
运行结果: