XML文件如下:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<books>
<book name="book1" num="1" > 出版于1991年 </book>
<book name="book2" num="2" > 出版于1992年 </book>
<book name="book3" num="3" > 出版于1993年 </book>
<book name="book4" num="4" > 出版于1994年 </book>
</books>
解析后的结果:
封装model来接收解析后的XML文件数据
JRBook.h文件
#import <Foundation/Foundation.h>
@interface JRBook : NSObject
//书籍名称
@property (nonatomic,copy)NSString * name;
//书籍数量
@property (nonatomic,assign) NSInteger number;
//出版年份
@property (nonatomic,copy) NSString * punDate;
+ (JRBook *) getBookWithDic:(NSDictionary *) dic;
@end
JRBook.m文件
#import "JRBook.h"
@implementation JRBook
+ (JRBook *) getBookWithDic:(NSDictionary *) dic
{
JRBook * book=[[JRBook alloc]init];
book.name=dic[@"name"];
book.number=[dic[@"num"] integerValue];
return book;
}
@end
ViewController.m文件
#import "ViewController.h"
#import "JRBook.h"
@interface ViewController () <NSXMLParserDelegate>
{
JRBook * tempBook;
NSMutableString * tempPublic;
}
/** 存放model 的数组 */
@property (nonatomic,strong) NSMutableArray * dataArray;
@end
@implementation ViewController
#pragma mark - 懒加载
- (NSMutableArray *) dataArray
{
if (_dataArray==nil)
{
_dataArray=[NSMutableArray array];
}
return _dataArray;
}
#pragma mark - 程序入口
- (void)viewDidLoad {
[super viewDidLoad];
}
#pragma mark - 点击屏幕开始解析XML文件
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//1>>> 初始化parse对象
NSString * path=[[NSBundle mainBundle]pathForResource:@"xml.xml" ofType:nil];
NSData * data=[NSData dataWithContentsOfFile:path];
NSXMLParser * parse=[[NSXMLParser alloc]initWithData:data];
//2>>> 设置代理,监控解析
parse.delegate=self;
//3>>> 开始解析
[parse parse];
//4>>>
for(JRBook * book in self.dataArray)
{
NSLog(@"书籍名称: %@-----书籍数量: %li----出版年份:%@",book.name,book.number,book.punDate);
}
}
#pragma mark - 实现 NSXMLParserDelegate 的代理方法
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
//NSLog(@"start");
}
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
//NSLog(@"end");
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if([elementName isEqualToString:@"book"])
{
tempPublic=[NSMutableString string];
tempBook =[JRBook getBookWithDic:attributeDict];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if([elementName isEqualToString:@"book"])
{
tempBook.punDate=tempPublic;
[self.dataArray addObject:tempBook];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
[tempPublic appendString:string];
}
@end