NSXMLParser解析XML

对xml进行解析的标准有两种:sax以及dom。

 

首先这两种标准并不是针对java的,他们在各种语言环境下都可以实现。dom是真正的国际标准,sax是事实的标准,它不由任何商业组织维护,而是由一个非商业的组织在运作。就像iso7层模型和tcp/ip一样,虽然sax不是正式的标准,但是一点也不影响他在xml解析领域的地位。

 

dom实现的原理是把整个xml文档一次性读出,放在一个树型结构里。在需要的时候,查找特定节点,然后对节点进行读或写。他的主要优势是实现简单,读写平衡;缺点是比较占内存,因为他要把整个xml文档都读入内存,文件越大,这种缺点就越明显。

 

sax的实现方法和dom不同,他只在xml文档中查找特定条件的内容,并且只提取需要的内容。这样做占用内存小,灵活,正好满足我们的需求。他的缺点就是写,有些资料介绍了写入的方法,这里就不赘述了。

 

NSXMLParser实现的是sax方法解析xml文件。

 

xmlParseViewController.h

 

#import <UIKit/UIKit.h>

@interface xmlParseViewController : UIViewController<NSXMLParserDelegate> {
	NSMutableArray		*chatArray;
	NSString			*chatFile;
	
	NSMutableDictionary	*currentChatInfo;
	NSMutableString		*currentString;
    BOOL				storingCharacters;
	IBOutlet UITableView *table;
}

@end

 

xmlParseViewController.m

 

#import "xmlParseViewController.h"

@implementation xmlParseViewController

static NSString *kName_Chats = @"chats";
static NSString *kName_Chat = @"chat";
static NSString *kName_Speaker = @"speaker";
static NSString *kName_Text = @"text";

//开始处理xml数据,它会把整个xml遍历一遍,识别元素节点名称
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *) qualifiedName attributes:(NSDictionary *)attributeDict {
	if ([elementName isEqualToString:kName_Chats]) {
		[chatArray removeAllObjects];
	} else if ([elementName isEqualToString:kName_Chat]) {
		[currentChatInfo removeAllObjects];
	} else if ([elementName isEqualToString:kName_Speaker] || 
			   [elementName isEqualToString:kName_Text]) {
		[currentString setString:@""];
		storingCharacters = YES;
	}
}

//存储从parser:(NSXMLParser *)parser foundCharacters:(NSString *)string方法中获取到的信息
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
    if ([elementName isEqualToString:kName_Chats]) {
    } else if ([elementName isEqualToString:kName_Chat]) {
		[chatArray addObject:[NSDictionary dictionaryWithDictionary:currentChatInfo]];
    } else if ([elementName isEqualToString:kName_Speaker] || [elementName isEqualToString:kName_Text]) {
		[currentChatInfo setObject:[NSString stringWithString:currentString] forKey:elementName];
    }
    
    storingCharacters = NO;
}

//得到文本节点里存储的信息数据
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    if (storingCharacters) [currentString appendString:string];
}

- (void)viewDidLoad {
    [super viewDidLoad];
	NSString *path=[[NSBundle mainBundle] pathForResource:@"chatLog" ofType:@"xml"];
	currentString = [[NSMutableString alloc] initWithCapacity:0];
	currentChatInfo = [[NSMutableDictionary alloc] initWithCapacity:2];
    chatArray = [[NSMutableArray alloc] initWithCapacity:0];
	[NSThread detachNewThreadSelector:@selector(loadThread:) toTarget:self withObject:path];
}

- (void) finshLoadFile {
	UITableView *tableView = (UITableView *)table;
	[tableView reloadData];
}

- (void) loadThread:(NSString *)xmlFile {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];	
	NSXMLParser *chatLogParser = [[NSXMLParser alloc] initWithContentsOfURL:[NSURL fileURLWithPath:xmlFile]];
	[chatLogParser setDelegate:self];
	[currentString setString:@""];
	[currentChatInfo removeAllObjects];
	
	[chatLogParser parse];
	[chatLogParser release];
	
	[self performSelectorOnMainThread:@selector(finshLoadFile) withObject:nil waitUntilDone:YES];
	[pool release];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [chatArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
		
		cell.backgroundColor = [UIColor colorWithRed:0.859f green:0.886f blue:0.929f alpha:1.0f];
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
	NSDictionary *chatInfo = [chatArray objectAtIndex:[indexPath row]];
    
	cell.textLabel.text = [chatInfo objectForKey:@"text"];
	cell.detailTextLabel.text = [chatInfo objectForKey:@"speaker"];
    return cell;
}

- (void)dealloc {
    [currentString release];
    [currentChatInfo release];
    [chatArray release];
    [super dealloc];
}

@end
 

主要就是实现NSXMLParserDelegate中的三个解析的方法。

你可能感兴趣的:(ios,xml,iPhone,NSXMLParser)