一、直接使用系统自带的NSXMLParser
#import "AppDelegate.h"
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate,UITableViewDataSource,UITableViewDelegate,NSXMLParserDelegate>//第四个是xml解析代理协议
{
NSMutableArray *_elementArr;//用来接收内容的数组,这个要反复的实力化,指空,释放
}
@property (strong, nonatomic) UIWindow *window;
@property(nonatomic,retain)NSMutableArray *dataArr;//table 数据源
@end
@implementation AppDelegate
-(void)dealloc
{
self.dataArr = nil;
[super dealloc];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
self.dataArr = [NSMutableArray arrayWithCapacity:0];
[self makeUI];
[self loadData];
[self.window makeKeyAndVisible];
return YES;
}
//table
-(void)makeUI
{
UITableView *table = [[UITableView alloc]initWithFrame:self.window.bounds style:UITableViewStylePlain];
table.dataSource = self;
table.delegate = self;
[self.window addSubview:table];
[table release];
table.tag = 6666;
}
//准备数据,本地的xml文
-(void)loadData
{
//1.读数据
NSString *path = [[NSBundle mainBundle]pathForResource:@"xml" ofType:@"txt"];
NSData *data = [NSData dataWithContentsOfFile:path];
//data就是xml.txt里的内容
//2.准备开始解析(实力化,代理,开始)
NSXMLParser *parse = [[NSXMLParser alloc]initWithData:data];//用 data 来初始化解析对象
parse.delegate = self;
parse.shouldProcessNamespaces = NO;//命名空间是否提取
[parse parse];// 开始解析
}
//发现左节点调用,第二个参数就是这个节点的名字(elementName),最后一个参数就是这个节点的属性
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
NSLog(@"左节点开始%@",elementName);
if ([elementName isEqualToString:@"book"]) { //发现了book的左节点的时候,表示一本书的解析开始了,这时候我们实力化成员变量那个全局的数组
if (!_elementArr) { //数组为空时
_elementArr = [[NSMutableArray alloc]initWithCapacity:0];
}
//当进入当前if表示,我们再book左节点,这里有属性,属性都存在了attributedict这个字典里,就是字典的key&value方法取值就可以
NSString *idStr = attributeDict[@"id"];
NSString *language = attributeDict[@"language"];
NSLog(@"id is %@,language is%@",idStr,language);
}
}
//找到当前节点(上面代理正发现的那个节点)调用,第二个参数就是这个节点的内容(string)
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
NSLog(@"发现内容%@",string);