`
toyota2006
  • 浏览: 545588 次
  • 性别: Icon_minigender_1
  • 来自: 石家庄
社区版块
存档分类
最新评论

iPhone/iPad 开发: 解析本地/网络上的xml文件(实例建附件)

XML 
阅读更多
1、解析本地xml文件

//找到本地test.xml文件
 NSString*path = [[NSBundlemainBundle]   pathForResource:@"test"ofType:@"xml"];
 NSFileHandle*file = [NSFileHandlefileHandleForReadingAtPath:path];
 NSData*data = [file readDataToEndOfFile];//得到xml文件

//开始解析
NSXMLParser* xmlRead = [[NSXMLParseralloc] initWithData:data];//初始化NSXMLParser对象
[data release];
[xmlRead setDelegate:self];//设置NSXMLParser对象的解析方法代理
[xmlRead parse];//调用代理解析NSXMLParser对象,看解析是否成功


2、解析网络xml文件

#define URIString @"http://192.168.247.76:8899/hisyo_cn/test.xml"
//首先链接网络文件
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:URIString]  cachePolicy:NSURLRequestUseProtocolCachePolicy  timeoutInterval:15];
	NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
	if (theConnection) {
                //得到文件数据
		receivedData=[[NSMutableData data] retain];
	} 
	else
	{
		NSLog(@"error");
	}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [receivedData appendData:data];
	
}

- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error
{
    [connection release];
    [receivedData release];
    NSLog(@"Error");
   //超过设定好的链接时间显示链接失败
    [theContent setText:@"Connection defeat"];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	NSString *content = [[NSString alloc] initWithData: receivedData encoding: NSUTF8StringEncoding];
	NSLog(@"content: %@",content);
	[theContent setText:content];
        //开始解析获取的receivedData
	xmlRead = [[NSXMLParser alloc] initWithData:receivedData];
	[xmlRead setDelegate:self];//设置NSXMLParser对象的解析方法代理
	[xmlRead parse];//调用代理解析NSXMLParser对象,看解析是否成
	//NSString *content = [[NSString alloc] initWithData: receivedData encoding: NSJapaneseEUCStringEncoding];

	[connection release];
	[receivedData release];
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics