通过NSXMLParser来解析XML
创建一个名为MyXML.xml文件
<?xml version = "1.0" encoding = "UTF-8" ?>
<root>
<person id = "1">
<firstName>Anthony</firstName>
<lastName>Robbins</lastName>
<age>51</age>
</person>
<person id = "2">
<firstName>Richard</firstName>
<lastName>Branson</lastName>
<age>61</age>
</person>
</root>
定义一个NSXMLParser类型的属性
#import <UIKit/UIKit.h>
@class ViewController;
@interface AppDelegate : UIResponder <UIApplicationDelegate,NSXMLParserDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) ViewController *viewController;
@property (strong, nonatomic) NSXMLParser *xmlParser;
@end
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSString *xmlFilePath = [[NSBundle mainBundle]pathForResource:@"MyXML" ofType:@"xml"];
NSData *xml = [[NSData alloc]initWithContentsOfFile:xmlFilePath];
xmlParser = [[NSXMLParser alloc]initWithData:xml];
xmlParser.delegate = self;
if([xmlParser parse]){
NSLog(@"The XML is parsed");
}else{
NSLog(@"Failed to parse the XML");
}
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease];
//self.window.rootViewController = self.viewController;
UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:self.viewController];
[self.window addSubview:nav.view];
[self.window makeKeyAndVisible];
return YES;
}
首先把文件内容读取到一个NSData实例对象中,然后使用initWithData:来初始化我们的XML parser,并把我们从xml文件中读取出来的数据传进去。之后我们可以调用XML parser的parser方法来开始解析处理。这个方法会zus当前线程,直至解析处理结束。
parserDidStartDocument:解析开始的时候调用该方法。
parserDidEndDocument:解析结束的时候调用该方法。
parser:didStartElement:namespaceURI:qualifiedName:attributes:在XML document中,当解析器在解析的时候遇到了一个新的element时会被调用该方法。
parser:didEndElement:namespaceURI:qualifiedName:当前节点结束之后会调用。
parser:foundCharacters:当解析器在解析文档内容的时候被调用。