iOS_OC 解析XML文件

NSXMLParserDelegate

/* 开始解析xml文件,在开始解析xml节点前,通过该方法可以做一些初始化工作 */
- (void)parserDidStartDocument:(NSXMLParser *)parser
{

NSLog(@"开始解析xml文件");

[spinner_view startAnimating];
newsTitles = nil;
newsDescription = nil;
newsPublicDates = nil;
tempString = nil;
showxml_textView.text = @"";
NSLog(@"开始解析xml文件");

}

/* 当解析器对象遇到xml的开始标记时,调用这个方法开始解析该节点 */
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
NSLog(@"发现节点");

if([elementName isEqualToString:@"title"])
{
if(newsTitles == nil)
newsTitles = [[NSMutableArray alloc] init];
}
else if([elementName isEqualToString:@"description"])
{
if(newsDescription == nil)
newsDescription = [[NSMutableArray alloc] init];
}
else if([elementName isEqualToString:@"pubDate"])
{
if(newsPublicDates == nil)
newsPublicDates = [[NSMutableArray alloc] init];
}
else {

}
}

/* 当解析器找到开始标记和结束标记之间的字符时,调用这个方法解析当前节点的所有字符 */
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
NSLog(@"正在解析节点内容");
if(self.tempString == nil)
self.tempString = [[NSMutableString alloc] init];
[self.tempString appendString:string];
}

/* 当解析器对象遇到xml的结束标记时,调用这个方法完成解析该节点 */
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
NSLog(@"解析节点结束");
if([elementName isEqualToString:@"title"])
{
[newsTitles addObject:self.tempString];
}
else if([elementName isEqualToString:@"description"])
{
[newsDescription addObject:self.tempString];
}
else if([elementName isEqualToString:@"pubDate"])
{
[newsPublicDates addObject:self.tempString];
}
else {

}
self.tempString = nil;
}

/* 解析xml出错的处理方法 */
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
NSLog(@"解析xml出错:%@", parseError);
}

/* 解析xml文件结束 */
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
if (!tempString) {
tempString = [[NSMutableString alloc] init];
}
for (int i = 2; i < 10; i++) {
[tempString appendString:newsTitles[i + 1]];
[tempString appendString:newsDescription[i]];
[tempString appendString:newsPublicDates[i]];
[tempString appendString:@"\n------------------------------------------------"];
}

showxml_textView.text = tempString;
NSLog(@"解析xml文件结束");
[spinner_view stopAnimating];
}

posted @ 2016-10-20 09:37  LZ每天进步一点点  阅读(1095)  评论(0编辑  收藏  举报