@interface TRBookXmlParser : NSObject<NSXMLParserDelegate>
@property (nonatomic, strong)NSMutableArray *books;
@property (nonatomic, strong)TRBook *book;
@property (nonatomic, copy)NSString *currentString;
-(NSMutableArray *)beginParseByPath:(NSString *)path;
@implementation TRBookXmlParser
-(NSMutableArray *)beginParseByPath:(NSString *)path{
NSData *data = [NSData dataWithContentsOfFile:path];
NSXMLParser *parser = [[NSXMLParser alloc]initWithData:data];
self.books = [NSMutableArray array];
parser.delegate = self;
if ([parser parse] ) {
NSLog(@"解析成功");
}
return self.books;
}
// step 2:准备解析节点
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
if ([elementName isEqualToString:@"book"]) {
NSLog(@"%@ ",attributeDict);
self.book = [[TRBook alloc]init];
self.book.bookID = [attributeDict objectForKey:@"id"];
[self.books addObject:self.book];
}
}
//step 3:获取首尾节点间内容
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
// 如果为‘\n’就回到第二步,如果不是‘\n’就到第四步
self.currentString = string;
}
//step 4 :解析完当前节点
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
NSLog(@"end %@",elementName);
if ([elementName isEqualToString:@"name"]) {
self.book.name = self.currentString;
}else if ([elementName isEqualToString:@"author"]) {
self.book.author = self.currentString;
}else if ([elementName isEqualToString:@"price"]) {
self.book.price = self.currentString.intValue;
}else if ([elementName isEqualToString:@"page"]) {
self.book.page = self.currentString.intValue;
}
}